2016-10-03 115 views
-1

我看過各種SO問題,但找不到與我的情況相似的問題。我有以下EF模型生成的類實體框架多對多關係保存導致錯誤

public partial class Resource 
{ 
    public Resource() 
    { 
     this.Roles = new HashSet<Role>(); 
    } 

    public int Id { get; set; } 
    public string Name { get; set; } 

    public virtual ICollection<Role> Roles { get; set; } 
} 

public partial class Role 
{ 
    public Role() 
    { 
     this.Resources = new HashSet<Resource>(); 
     this.Users = new HashSet<User>(); 
    } 

    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
    public Nullable<bool> Active { get; set; } 

    public virtual ICollection<Resource> Resources { get; set; } 

    public virtual ICollection<User> Users { get; set; } 
} 

public aysnc Task<int> SaveRelationship(params) 
{ 
    var db = GetContext(); 
    var role = await db.Roles.FirstOrDefaultAsync(...); 
    var resource = await db.Resources.FirstOrDefaultAsync(...); 
    role.Resources.Add(resource); 
    //tried these one at a time as well as together 
    resource.Roles.Add(role); 
    return await db.SaveChangesAsync(); 
} 

我得到錯誤的INSERT語句衝突與外鍵約束..

它生成/執行SQL查詢是:我知道這種說法將無法運行,我可以改變什麼,以便產生正確的聲明?

exec sp_executesql N'INSERT [Config].[RoleResourceAllocations]([RoleId]) 
VALUES (@0) 
SELECT [ResourceId] 
FROM [Config].[RoleResourceAllocations] 
WHERE @@ROWCOUNT > 0 AND [ResourceId] = scope_identity() AND [RoleId] = @0',N'@0 int',@0=1 

這是我的表

CREATE TABLE [Config].[RoleResourceAllocations] 
(
    [ResourceId] [int] IDENTITY(1,1) NOT NULL, 
    [RoleId] [int] not null, 

    CONSTRAINT [FK_RoleResourceAllocations_Roles] 
     FOREIGN KEY ([RoleId]) REFERENCES [Identity].[Roles]([Id]), 
    CONSTRAINT [FK_RoleResourceAllocations_Resources] 
     FOREIGN KEY ([ResourceId]) REFERENCES [Config].[Resources]([Id]), 
    CONSTRAINT [PK_RoleResourceAllocations] 
     PRIMARY KEY ([RoleId], [ResourceId]) 
) 
+0

我在過去用實體和具有關係的複雜實體以及「SaveChangesAsync()」添加了問題。與您正在經歷的非常相似,它幾乎就像是關鍵不會返回到其他表格所執行的其餘工作。你有沒有試過轉換函數非異步? –

+0

你真的需要做'role.Resources.Add(resource);'和'resource.Roles.Add(role);'?其中任何一個都應該填充由許多關係生成的交界表 – Developer

回答

0

這是一個典型的設置,所以你不應該有任何問題。

[配置] [RoleResourceAllocations] .ResourceId

應該是一個標識列,因爲你從

[配置] [資源]獲取價值。[ID]

柱。

我的其他建議是讓它工作爲同步,然後用異步的東西。

+0

我不能相信我錯過了這一點。愚蠢的錯誤。感謝您指出。 – CodeReaper

0

如果你試圖寫在同一時間一個新的角色和新的資源和兩個表有一個外鍵約束,它會拋出一個錯誤每因爲外鍵還不存在於任何項目的數據庫中(至少使用Oracle)。

有一個解決辦法:寫的第一個項目將在外國鍵列空,然後從第一個項目的關鍵寫的第二個項目。最後用第二個關鍵字更新第一個項目。

您可能會考慮更改應用程序的設計以避免這種情況。