Click here to Skip to main content
15,881,204 members
Articles / Database Development

One to Zero/One Relation in Entity Framework Code First

Rate me:
Please Sign up or sign in to vote.
4.36/5 (12 votes)
13 Aug 2014CPOL2 min read 61.9K   504   16   12
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, especially working with combinations of keywords like HasOptional with WithRequired, WithOptionalPrincipal, WithOptionalDependent.

So let’s see how we can use combinations of these keywords, to make relation between Tables. And what different structured tables are being 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
C#
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; }
}

Option 1: HasOptional then WithRequired

Configure relation: from Student configuration

Student configuration:

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

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

StudentContact configuration:

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

Image 1

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

Option 2: HasOptional then WithOptionalPrincipal

Configure relation: from Student configuration

Student configuration:

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

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

StudentContact configuration:

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

Image 2

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 nullable and foreign key from Student's Id column

Option 3: HasOptional then WithOptionalDependent

Configure relation: from Student configuration.

Student configuration:

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

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

StudentContact configuration:

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

Image 3

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 nullable 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 may we do … !!!

Option1Mimic: HasRequired then WithOptional

Configure relation: from StudentContact configuration.

StudentContact configuration:

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

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

Student configuration:

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

which would be the same as Option1:

Option2Mimic: HasRequired then WithOptional

Configure relation: from StudentContact configuration.

StudentContact configuration:

C#
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:

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

which would be the 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 properties which I have avoided.

Find Visual Studio 2010 (can be runnable in VS2013) solution of framework 4 project in the attachment. If you run the project, it would create a "UMS" database with 2 tables and data, 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)


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseThank u so much Pin
Member 946071915-May-19 21:15
Member 946071915-May-19 21:15 
QuestionOption 2 not nullable Pin
Cyril03517-Oct-18 2:10
Cyril03517-Oct-18 2:10 
GeneralOption 1 - consequences Pin
Piotr Dec14-Jul-18 14:41
Piotr Dec14-Jul-18 14:41 
QuestionOne to zero/one relation in entity framework code first Pin
İsa KAYA23-Apr-18 9:13
İsa KAYA23-Apr-18 9:13 
QuestionOption2 Pin
seawerst13-Jan-16 9:46
seawerst13-Jan-16 9:46 
SuggestionRe: Option2 Pin
DiponRoy13-Jan-16 22:30
DiponRoy13-Jan-16 22:30 
GeneralInformative & helpful boss Pin
Nitol Neophyte14-Aug-14 6:56
Nitol Neophyte14-Aug-14 6:56 
GeneralRe: Informative & helpful boss Pin
DiponRoy7-Apr-19 18:00
DiponRoy7-Apr-19 18:00 
QuestionNice explanation Pin
Thelonious Monk14-Aug-14 2:58
Thelonious Monk14-Aug-14 2:58 
AnswerRe: Nice explanation Pin
DiponRoy14-Aug-14 7:49
DiponRoy14-Aug-14 7:49 
Obviously option1
GeneralMy vote of 3 Pin
Darshan1229113-Aug-14 19:48
Darshan1229113-Aug-14 19:48 
QuestionRe: My vote of 3 Pin
DiponRoy7-Apr-19 17:59
DiponRoy7-Apr-19 17:59 

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

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