Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Zero Or One to Zero Or One relationship in EF Code first by Fluent API

I have two POCO classes:

Order Class:

public class Order {     public int Id { get; set; }     public int? QuotationId { get; set; }     public virtual Quotation Quotation { get; set; }     .... } 

Quotation Class:

public class Quotation {     public int Id { get; set; }      public virtual Order Order { get; set; }     ....    } 
  • Each Order may be made from one or zero quotation, and
  • each quotation may cause an order.

So I have an "one or zero" to "one or zero" relation, how can I implement this, in EF Code first by Fluent API?

like image 712
Masoud Avatar asked Feb 05 '13 06:02

Masoud


People also ask

What is a one to zero relationship?

A one-to-zero-or-one relationship happens when a primary key of one table becomes PK & FK in another table in a relational database such as SQL Server.

How will you create relationship between tables in Entity Framework?

You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B.

How do I code first in Entity Framework?

Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…


1 Answers

By changing pocos to:

public class Order {     public int OrderId { get; set; }     public virtual Quotation Quotation { get; set; } } public class Quotation {     public int QuotationId { get; set; }     public virtual Order Order { get; set; } } 

and using these mapping files:

public class OrderMap : EntityTypeConfiguration<Order> {     public OrderMap()     {         this.HasOptional(x => x.Quotation)             .WithOptionalPrincipal()             .Map(x => x.MapKey("OrderId"));     } }  public class QuotationMap : EntityTypeConfiguration<Quotation> {     public QuotationMap()     {         this.HasOptional(x => x.Order)             .WithOptionalPrincipal()             .Map(x => x.MapKey("QuotationId"));     } } 

we will have this DB(that means 0..1-0..1):

enter image description here

with special thanks to (Mr. Vahid Nasiri)

like image 178
Masoud Avatar answered Sep 28 '22 23:09

Masoud