Header:
Id => identity, primary key
...other columns...
Detail:
Id => identity, primary key
HeaderId => foreign key
...other columns...
public bool CreateHeader(Header header, IEnumerable<Detail> details)
{
using (TransactionScope tran = new TransactionScope())
using (TemplateEntities ctx = new TemplateEntities())
{
try
{
HeaderRepository ihRep = new HeaderRepository(ctx);
DetailRepository idRep = new DetailRepository(ctx);
ihRep.Add(header);
// header.Id is still 0
foreach (Detail detail in details)
{
detail.HeaderId = header.Id;
idRep.Add(detail);
}
ctx.SaveChanges();
tran.Complete();
return true;
}
catch
{
return false;
}
}
}
答案 0 :(得分:1)
您是否尝试过使用Navigation属性而不是FK属性?
尝试将foreach的主体切换为:
detail.Header = header;
这应告知EF关系,它应该从那里管理它。如果您的idRep.Add执行任何其他工作,我建议将其拉出到另一种方法,您可以调用它而不尝试将细节添加到EF上下文。