Click here to Skip to main content
11,412,159 members (62,804 online)
Click here to Skip to main content

One to zero/one relation in entity framework code first

, 13 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Here we will see how to configure one to zero/one relation between two entities in Entity Framework Code First

Introduction

Working with entity framework code first is interesting. But last week I faced some problems to configure One to Zero or One relation between entities. Specially working with combinations of key words like HasOptional with WithRequired, WithOptionalPrincipal, WithOptionalDependent.

So let’s see how we can use combinations of these key words, to make relation between Tables. And what different structured tables are been populated for being different in combinations.  

Background

Let’s say we have two entities Student and StudentContact. Where a

  • Student may only have a contact (StudentContact) or not
  • But Every contact (StudentContact) must have a Student
public class Student
{
    public long Id { get; set; }
    public string Name { get; set; }
    /*May have a contact or not*/
    public virtual StudentContact Contact { get; set; }
}

public class StudentContact
{
    public long Id { get; set; }
    public string ContactNumber { get; set; }
    /*Must have a Student*/
    public virtual Student Student { get; set; }
}

Option1: HasOptional then WithRequired

Configure relation: from Student configuration

Student configuration

HasKey(x => x.Id);
Property(x => x.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

HasOptional(x => x.Contact)
    .WithRequired(l => l.Student);

StudentContact configuration

HasKey(x => x.Id);
Property(x => x.Id)
    .HasColumnName("Student_Id")
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

      

Student:

  • Id is primary key with auto increment

StudentContact:

  • Id (Student_Id as we customized) is both primary key and foreign key from Student's Id column

Option2: HasOptional then WithOptionalPrincipal

Configure relation: from Student configuration

Student configuration

HasKey(x => x.Id);
Property(x => x.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

HasOptional(x => x.Contact)
    .WithOptionalPrincipal(l => l.Student);

StudentContact configuration

HasKey(x => x.Id);
Property(x => x.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

                 

Student:

  • Id is primary key with auto increment

StudentContact:

  • Id is primary key with auto increment
  • Student_Id is automatically created and has no navigation property in StudentContact/Student  entity
  • Student_Id is not null able and foreign key from Student's Id column

Option3: HasOptional then WithOptionalDependent

Configure relation: from Student configuration

Student configuration

HasKey(x => x.Id);
Property(x => x.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

HasOptional(x => x.Contact)
    .WithOptionalDependent(l => l.Student);

StudentContact configuration

HasKey(x => x.Id);
Property(x => x.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

                

Student:

  • Id is primary key with auto increment
  • Contact_Id is automatically created and has no navigation property in StudentContact/Student entity
  • Contact_Id is null able foreign key from StudentContact’s Id column

StudentContact:

  • Id is primary key with auto increment

 

Well some books described it like,

Selecting WithRequiredPrincipal will make the entity that you are configuring the principal, meaning it contains the primary key of the relationship.

 Selecting WithRequiredDependent will make the entity that you are configuring the dependent, meaning it will have the foreign key of the relationship.

Interesting Thing !!!

Until now we have configured relation from Student configuration, But Let’s say we want to configure relations from the Student Contact configuration, so what we may do … !!!

Option1Mimic: HasRequired then WithOptional

Configure relation: from StudentContact configuration

StudentContact configuration

HasKey(x => x.Id);
Property(x => x.Id)
    .HasColumnName("Student_Id")
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

HasRequired(x => x.Student)
    .WithOptional(l => l.Contact);

Student configuration

HasKey(x => x.Id);
Property(x => x.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

which would be same as Option1

Option2Mimic: HasRequired then WithOptional

Configure relation: from StudentContact configuration

StudentContact configuration

HasKey(x => x.Id);
Property(x => x.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

HasRequired(x => x.Student)
    .WithOptional(l => l.Contact)
    .Map(x => x.MapKey("Student_Id"));

Student configuration

HasKey(x => x.Id);
Property(x => x.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

which would be same as Option2

Option3Mimic: HasRequired then WithOptional

Unable to configure relation from StudentContact configuration

Limitations

  1. Yes there could be some errors which I haven't faced yet, or could make some ethical disturbance. So if you find any just let me know.
  2. There are some issues like navigation property’s which I have avoided.

 

Find visual studio 2010(Can be runnable at VS2013) solution of framework 4 project at the attachment. If you run the project it would create a "UMS" database with 2 tables and datas, at the local machine. You can change it using app.config.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DiponRoy

Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
GeneralInformative & helpful boss PinmemberNeophyte Nitol14-Aug-14 7:56 
QuestionNice explanation PinmemberFernando Bracaroto14-Aug-14 3:58 
AnswerRe: Nice explanation Pinmemberdiponsust14-Aug-14 8:49 
GeneralMy vote of 3 PinmemberDarshan1229113-Aug-14 20:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150414.5 | Last Updated 14 Aug 2014
Article Copyright 2014 by DiponRoy
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid