如何在Eager Loaded类中保存值?

时间:2012-08-07 14:05:11

标签: c# entity-framework eager-loading edmx

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

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

编写此更新的正确方法是什么?

------ --------更新

如果删除edmx模型中的<DefiningQuery>部分,则急切加载将在LINQ语句的.include("Roles")部分失败。

另外,我在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_FKRoleId_FK

1 个答案:

答案 0 :(得分:2)

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

您可以在MSDN论坛上找到一些可能的解决方案:Unable to update the EntitySet