【发布时间】:2011-12-27 09:15:05
【问题描述】:
假设我有这个表结构:
Client
-----------
ClientId int not null (identity)
CurrentDemographicId int null (FK to ClientDemographic)
OtherClientFields varchar(100) null
ClientDemographic
------------------
ClientDemographicId int not null (identity)
ClientId int not null (FK to Client)
OtherClientDemographicFields varchar(100) null
这个想法是客户端(在 EF 中)将有一个 ClientDemographics 列表和一个 CurrentDemographic 属性。
问题是当我设置对象结构并尝试保存它时,我得到了这个错误:
无法确定相关操作的有效顺序。由于外键约束、模型要求或存储生成的值,可能存在依赖关系
这个错误是有道理的。我的表格设置中有一个循环引用。它不知道先插入哪个实体(因为它同时需要两个表中的 Id)。
所以,我拼凑了一个如下所示的解决方案:
// Save off the unchanged ClientDemograpic
ClientDemographic originalClientDemographic = client.CurrentClientDemographic;
// Merge the contract into the client object
Mapper.Map(contract, client);
// If this is a new client then add as new to the list.
if (client.ClientId == 0)
{
dataAccess.Add(client);
}
// Restore the original ClientDemographic so that EF will not choke
// on the circular reference.
ClientDemographic newClientDemographic = null;
if (client.CurrentClientDemographic != originalClientDemographic)
{
newCurrentClientDemographic = client.CurrentClientDemographic;
client.CurrentClientDemographic = originalClientDemographic;
}
// save our changes to the db.
dataAccess.SaveChanges();
// Restore updates to ClientDemographics and save (if needed)
if (newClientDemographic != null)
{
client.CurrentClientDemographic = newCurrentClientDemographic;
dataAccess.SaveChanges();
}
但是将引用更改回以前的值,保存,然后再次设置它以便我可以再次保存感觉就像一个 hack。
是否有更简洁的方法来处理 EF 中的循环引用?
【问题讨论】:
标签: c# entity-framework entity-framework-4 circular-dependency