Using .NET 4, MVC 4, Entity Framework 5, SQL Server;
I want to insert in one transaction a new Header record and several new HeaderData records which all have a Foreign Key to the inserted Header record. Header record has an Identity int Primary Key.
Entities.Header h = new Entities.Header();
h.Name = name;
h.Time = DateTime.Now;
h.Comments = comments;
db.Headers.Add(h);
// db.SaveChanges(); // Save changes here?
// and get ID to use below via h.ID?
foreach (DataRecord dr in datarecords) // my own custom types here
{
Entities.HeaderData hd = new Entities.HeaderData();
// hd.header = thisid // ?? this is the FK to Header.ID, its Identity int PK
hd.name = dr.name
hd.value = dr.value
db.HeaderDatas.Add(hd)
}
db.SaveChanges(); // or wait to save all here?
So problem is, I don't know what the header record ID is going to be to put in the data records' FK field until after it is committed. Or do I? Just referencing h.ID before the SaveChanges/Commit did not work, it returned 0.
Options: 1) Should I just commit the header record first, get the PK to use, then populate the data record models and commit them separately? Might have to do a rollback of the header in such case, sounds like a less than optimal way to go about it.
2) Should I be using a GUID PK or similar instead, where I create it here in the app? That is the only place the records can be added from anyway.
3) Is there a slick way in Entity Framework (temporary EntityKey maybe?), and have it do the transaction inserts so that it will automatically put the right header ID in the data records' FK fields? This seems doable to EF but I couldn't exactly find a reference to it.