To add a role into my user and save it:
var user = DataContext.Users
.Include("Roles")
.Where(u => u.UserName.ToUpper() == username.ToUpper())
.FirstOrDefault();
foreach (string rolename in roleNames)
{
var role = FindRoleByName(rolename);
user.Roles.Add(role);
DataContext.Entry(user).State = EntityState.Modified; // probably not needed
DataContext.SaveChanges();
}
But it throws the exception
[System.Data.Entity.Infrastructure.DbUpdateException]
{"Unable to update the EntitySet 'UserRoles' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation."} System.Data.Entity.Infrastructure.DbUpdateException
What is the correct way to write this update?
------Update--------
If I remove the <DefiningQuery>
section in the edmx model, the eager loading will fail at .include("Roles")
part in the LINQ statement.
Also, I found some error comment in the edmx (in xml editor). I guess that is where the problem is. It says:
<!--Errors Found During Generation:
warning 6002: The table/view 'DNR.dbo.UserRoles' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.
-->
So, do I have to add a primary key in the joining table along with my UserId_FK
and RoleId_FK
?