In ASP .NET MVC 5 , I am trying to save multiple rows of permissions by the use of foreach
this is my model:
public class RoleClaims
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public string RoleId { get; set; }
public string Type { get; set; }
public string Value { get; set; }
}
Then I moved to Context :
public DbSet<RoleClaims> RoleClaims { get; set; }
Then I did migration it works:
/****** Script for SelectTopNRows command from SSMS ******/
SELECT TOP (1000) [id]
,[RoleId]
,[Type]
,[Value]
FROM [no].[dbo].[RoleClaims]
,so know I am trying to save 4 permission by the use of foreach so this is my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Generatepermission(string roleId, string module)
{//geting id
var role = await _roleManager.FindByIdAsync(roleId);
//getting role
var claims = await _roleManager.GetClaimsAsync(role);
var Permssion = new RoleClaims();
if (ModelState.IsValid)
{
try
{
//declare the verible
var Permssion1 = "Permissions." + module + ".Create";
var Permssion2 = "Permissions." + module + ".View";
var Permssion3 = "Permissions." + module + ".Edit";
var Permssion4 = "Permissions." + module + ".Delete";
//object equal the coming value
string[] Permssionarry = { Permssion1 , Permssion2, Permssion3, Permssion4 };
foreach (var claim in Permssionarry)
{
Permssion.Value = claim;
Permssion.RoleId = roleId;
Permssion.Type = "Permission";
_context.Add(Permssion);
await _context.SaveChangesAsync();
}
}
catch (DbUpdateConcurrencyException) {
throw;
}
}
return RedirectToAction("Index");
}
When I run the code the first Permssion1 is only saved when it reach to Permssion2 it gives me this error:
SqlException: Cannot insert explicit value for identity column in table 'RoleClaims' when IDENTITY_INSERT is set to OFF.
I don't know what is the source of error, can any one help? can I save multiple rows by on click in .net