Let's say I have two tables, A and B, whereA has a foreign key pointing to B.
Here's how the database might look:
A: | B:
|
id (int) | b (foreign B) | id (int)
---------+-------------- | --------
1 | 2 | 2
2 | 5 | 5
3 | 2 |
I now wish to insert both a new object of type A and a new object of type B into the database, with the new A referencing the new B. Also, they must both be inserted within the same transaction, as I cannot allow e.g. that only the B gets inserted, but A fails.
However, I don't know how to insert A without first separately inserting B, as I only get to know B.id after B is inserted: B.id gets assigned by the database as an incrementing primary key.
This is what I'd like to write, but cannot:
b = new B { };
a = new A { b = b };
db.Add(b);
db.Add(a);
db.SaveChanges()
How can I accomplish this using Entity Framework?
Thanks!