将角色添加到我的用户并保存:
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();
}
但它抛出异常
[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
编写此更新的正确方法是什么?
- - - 更新 - - - -
如果我删除<DefiningQuery>
edmx 模型中的部分,则预先加载将.include("Roles")
在 LINQ 语句中部分失败。
另外,我在 edmx(在 xml 编辑器中)中发现了一些错误注释。我想这就是问题所在。它说:
<!--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.
-->
那么,我是否必须在加入表中添加一个主键以及我的UserId_FK
and RoleId_FK
?