[英]Updating a many-to-many relation using GraphDiff cause an error
我在我的应用程序中EF code first 6.1
使用带有.NET 4
EF code first 6.1
,并在我的模型中使用以下类(我剪切了其他不相关的图部分。例如, Permission
有其他导航):
我的业务逻辑适用于分离的实体,因此我使用RefactorThis.GraphDiff 2.0.1.0
来执行更新。 我想更新一个applicationUserInApplication
对象,所以我从数据库获取一个现有的applicationUserInApplication
及其SecurityRole
,并将其作为View-Model
返回然后更新它并使用Automapper
将其映射回applicationUserInApplication
(在更新操作中,我只更改SecurityRoles
集合一个applicationUserInApplication
,这些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_Mapping
类中为AppUserInApplication
定义了以下映射:
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();
我收到以下错误:
EntityFramework.dll中出现未处理的“System.InvalidOperationException”类型异常附加信息:操作失败:由于一个或多个外键属性不可为空,因此无法更改关系。 当对关系进行更改时,相关的外键属性将设置为空值。 如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。
[更新]
我也尝试过映射
_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获取它
该异常意味着实体框架抱怨您已根据需要映射但未设置的导航属性(它们为空)。 在调试示例代码之后,除了安全角色之外,所有导航属性都是如此。
如果您更改代码如下:
导航属性已设置,一切都按预期工作。
我查看了你的代码,我认为问题出在你的映射中。 AppUserInApplication表与表SecurityRoles具有多对多关系,并且在您的映射中使用“OwnedCollection” - 应该在一对多或一对一关系中使用,请尝试使用AssociatedCollection。
_dbContext.UpdateGraph(appUserInApplication, map => map
.AssociatedCollection(t => t.SecurityRoles, with=> (....)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.