Click here to Skip to main content
14,088,376 members
Click here to Skip to main content
Add your own
alternative version

Stats

37.5K views
436 downloads
16 bookmarked
Posted 13 Aug 2014
Licenced CPOL

One to Zero/One Relation in Entity Framework Code First

, 13 Aug 2014
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, 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
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:

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

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

Option 3: 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 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:

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 the 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 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)

Share

About the Author

DiponRoy
Bangladesh Bangladesh
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
PraiseThank u so much Pin
Member 946071915-May-19 21:15
memberMember 946071915-May-19 21:15 
QuestionOption 2 not nullable Pin
Cyril03517-Oct-18 2:10
memberCyril03517-Oct-18 2:10 
GeneralOption 1 - consequences Pin
Piotr Dec14-Jul-18 14:41
memberPiotr Dec14-Jul-18 14:41 
QuestionOne to zero/one relation in entity framework code first Pin
İsa KAYA23-Apr-18 9:13
memberİsa KAYA23-Apr-18 9:13 
QuestionOption2 Pin
seawerst13-Jan-16 9:46
memberseawerst13-Jan-16 9:46 
SuggestionRe: Option2 Pin
DiponRoy13-Jan-16 22:30
memberDiponRoy13-Jan-16 22:30 
GeneralInformative & helpful boss Pin
Kumar Nitol14-Aug-14 6:56
memberKumar Nitol14-Aug-14 6:56 
GeneralRe: Informative & helpful boss Pin
DiponRoy7-Apr-19 18:00
memberDiponRoy7-Apr-19 18:00 
QuestionNice explanation Pin
Thelonious Monk14-Aug-14 2:58
memberThelonious Monk14-Aug-14 2:58 
AnswerRe: Nice explanation Pin
DiponRoy14-Aug-14 7:49
memberDiponRoy14-Aug-14 7:49 
GeneralMy vote of 3 Pin
Darshan1229113-Aug-14 19:48
memberDarshan1229113-Aug-14 19:48 
QuestionRe: My vote of 3 Pin
DiponRoy7-Apr-19 17:59
memberDiponRoy7-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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190518.1 | Last Updated 14 Aug 2014
Article Copyright 2014 by DiponRoy
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid