Reputation: 12646
Let's say I have two tables, Person and Address, which have a one-to-one relationship (one-to-one or one-to-zero to be precise.) Person has an Id field which is the PK and Address has a PersonId field which is the PK/FK and matches the Person PK. So far so good.
My problem is this - I save address at the same time I save person. Person's PK is auto-generated, so I end up doing this:
Is there a better way to do this? Making 3 db calls seems silly.
P.S. - feel free to edit the title, I couldn't summarize the q in a sentence.
Upvotes: 2
Views: 84
Reputation: 2866
Entity framework do it for you by itself. The way is, you need to fill you person entity as well as your address entity too.
For Example your Person entity model is
public class Person{
public int PersonId {get;set;}
public string PersonName {get;set;}
public Address PersonAddress{get;set;}
//You must have this field (PersonAddress) if you created model from
// database having both the tables relations.
}
Now your address entity model is
public class Address{
public string City{get;set;}
public string State {get;set;}
public string Country{get;set;}
public int PersonId{get;set;}
}
Now what you have to do is,
Fill your person entity as
Person person = new Person();
person.Name = "ABC";
person.PersonAddress = new Address(){ City="DEF", State = "OPQ", Country="XYZ", /*Leave PersonId*/ };
Save this entity in database
context.entity(person).state=EntityState.Added;
context.SaveChanges();
This will save both the entities, person and address and will also have relation in it. You can check that it will save PersonId in Address field.
Upvotes: 2
Reputation: 628
Use this command for the PK/FK of the 2nd insert:
LAST_INSERT_ID();
Upvotes: 0