VSO
VSO

Reputation: 12646

How to set up a one-to-one relationship in EntityFramework?

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:

  1. Save Person table fields.
  2. GET Person object I just saved from SQL (another call), and get its generated Id.
  3. Save Address table using the Id I got in step #2.

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

Answers (2)

Lali
Lali

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

CharlesEF
CharlesEF

Reputation: 628

Use this command for the PK/FK of the 2nd insert:

LAST_INSERT_ID();

Upvotes: 0

Related Questions