I have the following code:
var roleEditionCNT = new Role { ApplicationName = "TTT", RoleName = "EDITION_CNT" };
var roleEditionKCD = new Role { ApplicationName = "TTT", RoleName = "EDITION_KCD" };
var roleEditionInterne = new Role { ApplicationName = "TTT", RoleName = "EDITION_INTERNE" };
var roleConsultationInterne = new Role { ApplicationName = "TTT", RoleName = "CONSULTATION_INTERNE" };
var roleConsultationExterne = new Role { ApplicationName = "TTT", RoleName = "CONSULTATION_EXTERNE" };
var roleAdministrator = new Role { ApplicationName = "TTT", RoleName = "ADMINISTRATOR" };
new List<Role>
{
roleEditionCNT,
roleEditionKCD,
roleEditionInterne,
roleConsultationInterne,
roleConsultationExterne,
roleAdministrator
}.ForEach(b => context.Roles.AddOrUpdate(m => m.RoleName, b));
Then I can do:
var myUser = new User
{
Company = "DELTOY",
FirstName = "BRYAN",
LastName = "KENETH",
Roles = new List<Role> { roleEditionCNT }
};
Now I would like to modify the way I assign roles like this:
var myUser = new User
{
Company = "DELTOY",
FirstName = "BRYAN",
LastName = "KENETH",
Roles = new List<Role> { new Role { ApplicationName = "TTT", RoleName = "EDITION_CNT" } }
};
This code compiled successfully but at runtime I got the error:
Violation of PRIMARY KEY constraint ‘PK_Roles’. Cannot insert
duplicate key in object ‘dbo.Roles’
By simply modifying the above code, it seems the system is trying to add a new record to the table Roles. How can I simply assign Role but not using the variable. I prefer to give rolename with a string.
Any idea?
In the second example you are trying to add a User with a new Role as opposed to assigning it to an existing Role. The Role you are trying to add already exists in the Roles table.
You can get the Role object into a variable like.
and then assign it to the new User.