Mohamed Nuur
Mohamed Nuur

Reputation: 5655

EF Code First one to one relationship

I have the following situation:

public class User
{
   public int ID { get; set; }
   public string Name { get; set; }
   // ...
   public virtual Address Address { get; set; }
}

public class Address
{
   public int ID { get; set; }
   public string Street { get; set; }
   public string ZipCode { get; set; }
   // ...
   public int UserID { get; set; }
   public virtual User User { get; set; }
}

I can't for the life of me figure out how to setup the fluent mapping. I tried this:

void Map( DbModelBuilder modelBuilder )
{
    var entityConfiguration = modelBuilder.Entity<User>();
    entityConfiguration.HasKey( i => i.ID ).Property( i => i.ID ).HasColumnName( "UserID" );
    entityConfiguration.HasRequired(i => i.Address)
      .WithOptional(i => i.User);
    entityConfiguration.ToTable( "MyUser" );
}

But it's no good. It generates SQL that tries to join User.UserID = Address.AddressID

Upvotes: 1

Views: 216

Answers (1)

Alaa Masoud
Alaa Masoud

Reputation: 7135

EF is creating the correct relation for a one-to-one mapping. Your own column naming's may have confused you.

A one-to-one relation is defined as follows

User Table            Address Table
----------            -------------
UserId PK             UserID PK, FK
Name                  ZipCode

The primary key of child table (Address) will also be the foreign key to the parent table (User)

If you are going to include UserID column in Address table and make it a foreign key to User table then this will be a one-to-many relation not a one-to-one.

Upvotes: 2

Related Questions