0

将角色添加到我的用户并保存:

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_FKand RoleId_FK

4

1 回答 1

2

这听起来像是一个映射问题。例如,如果实体是从数据库视图映射和/或缺少主键,就会发生这种情况。

您可以在 MSDN 论坛上找到一些可能的解决方案:无法更新 EntitySet

于 2012-08-07T14:09:30.113 回答