How to insert in two related tables within the same context( how to retrieve the identity value before SaveChanges )?
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())
{开发者_如何学JAVA
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;
}
}
}
Have you tried using the Navigation property rather than the FK Property?
Try switching the body of your foreach to just:
detail.Header = header;
This should inform EF of the relationship and it should manage it from there IIRC. If your idRep.Add performs any other work I'd recommend pulling it out to another method that you can call without it trying to add the detail to the EF context.
精彩评论