Reputation: 3212
i wanna add and an entity and get its identity before savechanges() and set it as a foreign key of another entity before savechanges in entity framework code first. is it possible?
first model
public class A
{
int AId { get; set; }
string name { get; set; }
}
second model
public class B
{
int BId { get; set; }
int AId { get; set; }
string name { get; set; }
}
and.....
db.As.Add(A);
b.AId = A.Aid;
db.savechanges();
is there any article which explains how it works?
Upvotes: 1
Views: 167
Reputation: 32447
Declare a property of type A
in B
.
public class A
{
int AId { get; set; }
string name { get; set; }
}
public class B
{
int BId { get; set; }
virtual A A { get; set; }
int AId { get; set; }
string name { get; set; }
}
Then assign the instance of A
to that navigational property. EF will determine the insert/update order of entities resolve the FKs.
b.A = a;
db.As.Add(a);
db.savechanges();
Upvotes: 1