我在我的应用程序中使用EF code first 6.1和.NET 4,并在我的模型中有以下类(我剪切了图表中其他不相关的部分)。例如,Permission还有其他导航):

我的业务逻辑与独立实体一起工作,因此我使用RefactorThis.GraphDiff 2.0.1.0来执行更新。我想更新一个applicationUserInApplication对象,所以我从数据库中获得了一个现有的applicationUserInApplication及其SecurityRole,并将其作为View-Model返回,然后更新它并使用Automapper将其映射回applicationUserInApplication (在更新操作中,我只更改applicationUserInApplication的SecurityRoles集合,这些SecurityRole以前保存,我只选择它们),所以我定义了以下配置:
_dbContext.UpdateGraph(appUserInApplication, map => map
.OwnedCollection(t => t.SecurityRoles, with=>
with.AssociatedCollection(t=>t.Permissions)
.AssociatedEntity(t => t.ApplicationDescriptor))
.AssociatedEntity(t=>t.ApplicationDescriptor)
.AssociatedEntity(t=>t.AppUser)
.AssociatedEntity(t=>t.UserProfile));并为AppUserInApplication类中的AppUserInApplication_Mapping定义了如下映射:
this.HasRequired(t => t.AppUser).WithMany(t => t.AppUserInApplications).HasForeignKey(d => d.AppUserId);
this.HasRequired(t => t.Applicationdescriptor).WithMany(t => t.AppUserInApplications).HasForeignKey(d => d.ApplicationId);
this.HasMany(t => t.SecurityRoles).WithMany(t => t.AppUserInApplications)
.Map(m =>
{
m.ToTable("AppUserInApplicationSecurityRole");
m.MapLeftKey("AppUserInApplications_Id");
m.MapRightKey("SecurityRoles_Id");
});
this.HasRequired(t => t.UserProfile).WithMany().HasForeignKey(t=>t.UserProfileId);在调用上面的UpdateGraph()之后,当我调用_dbContext.SaveChange();时,会得到以下错误:
System.InvalidOperationException类型的未处理异常发生在EntityFramework.dll附加信息中:操作失败:由于一个或多个外键属性不可空,关系无法更改。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新的关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。
更新的
我也试着跟着映射
_dbContext.UpdateGraph(appUserInApplication, map => map
.AssociatedCollection(t => t.SecurityRoles)
.AssociatedEntity(t => t.Application)
.AssociatedEntity(t => t.UserProfile)
.AssociatedEntity(t => t.AppUser);但我也犯了同样的错误。
有人知道问题出在哪里吗?
更新的
我上传了我的模型的简化版本,您可以从https://www.dropbox.com/s/i9dvrb6ebd5wo7h/GraphdiffTest.rar?dl=0获得它
发布于 2014-10-26 11:35:40
异常意味着Entity正在抱怨您按需要映射的导航属性,但没有设置(它们为null)。调试示例代码之后,除了安全角色之外,您的所有导航属性都是这样。
如果您像这样更改代码:

导航属性被设置,并且一切都如您所期望的那样工作。
发布于 2014-09-22 12:11:14
我看过您的代码,我认为问题在于您的映射。AppUserInApplication表与表SecurityRoles有多对多的关系,在映射中使用"OwnedCollection“--应该在一对多或一对一的关系中使用,尝试使用AssociatedCollection。
_dbContext.UpdateGraph(appUserInApplication, map => map
.AssociatedCollection(t => t.SecurityRoles, with=> (....)https://stackoverflow.com/questions/25885568
复制相似问题