簡體   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