我看過各種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])
)
我在過去用實體和具有關係的複雜實體以及「SaveChangesAsync()」添加了問題。與您正在經歷的非常相似,它幾乎就像是關鍵不會返回到其他表格所執行的其餘工作。你有沒有試過轉換函數非異步? –
你真的需要做'role.Resources.Add(resource);'和'resource.Roles.Add(role);'?其中任何一個都應該填充由許多關係生成的交界表 – Developer