3

我在我的应用程序中使用EF code first 6.1with.NET 4并且在我的模型中有以下类(我剪切了图表的其他不相关部分。例如Permission有其他导航): 在此处输入图像描述

我的业务逻辑适用于分离实体,因此我RefactorThis.GraphDiff 2.0.1.0用于执行更新。我想更新一个applicationUserInApplication对象,所以我从数据库中获取一个现有applicationUserInApplicationSecurityRoles 并将其作为 a 返回,View-Model然后更新它并将其映射回applicationUserInApplicationusing Automapper(在更新操作中,我只更改SecurityRolesa 的集合applicationUserInApplication,这些SecurityRoles 之前保存,我只选择它们),所以我定义了以下配置:

_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();出现以下错误:

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获取

4

2 回答 2

3

该异常意味着实体框架抱怨您已按要求映射但未设置的导航属性(它们为空)。在调试您的示例代码之后,除安全角色之外的所有导航属性都是这种情况。

如果您像这样更改代码:

工作代码

导航属性已设置,一切都按您的预期工作。

于 2014-10-26T11:35:40.943 回答
0

我查看了您的代码,我认为问题出在您的映射中。AppUserInApplication 表与表 SecurityRoles 具有多对多关系,并且在您的映射中您使用了“OwnedCollection” - 它应该用于一对多或一对一关系,请尝试使用 AssociatedCollection。

  _dbContext.UpdateGraph(appUserInApplication, map => map
            .AssociatedCollection(t => t.SecurityRoles, with=> (....)
于 2014-09-22T12:11:14.207 回答