繁体   English   中英

使用GraphDiff更新多对多关系会导致错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM