Quantcast
Channel: Development With A Dot
Viewing all articles
Browse latest Browse all 404

Entity Framework Code First Relations

$
0
0

Introduction

This post is more for self-reference than anything else. Basically, I tend to forget some options for mapping relations with Entity Framework Code First, so I wrote this. If in doing so it helps someone, even better! Winking smile

One-to-Many

First, the most basic: one-to-many/many-to-one: an instance of the Master class has lots of Details.

   1:publicclass Master
   2: {
   3:public Int32 MasterId { get; set; }
   4:  
   5:publicvirtual ICollection<Detail> Details { get; protected set; }
   6: }

 

   1:publicclass Detail
   2: {
   3:public Int32 DetailId { get; set; }
   4:  
   5:publicvirtual Master Master { get; set; }
   6: }

image

One-to-One

The stepchild of database relations. Sometimes it is useful, though: a single Master has an optional Detail, which always refers to an existing Master.

   1:publicclass Master
   2: {
   3:public Int32 MasterId { get; set; }
   4:  
   5:publicvirtual Detail Detail { get; set; }
   6: }

 

   1:publicclass Detail
   2: {
   3:     [Key]
   4:     [ForeignKey("Master")]
   5:public Int32 MasterId { get; set; }
   6:  
   7:     [Required]
   8:publicvirtual Master Master { get; set; }
   9: }

image

Many-to-Many

A single Master can have many Details; each Detail can itself be connected to multiple Masters.

   1:publicclass Master
   2: {
   3:public Master()
   4:     {
   5:this.Details = new List<Detail>();
   6:     }
   7:  
   8:public Int32 MasterId { get; set; }
   9:  
  10:publicvirtual ICollection<Detail> Details { get; protected set; }
  11: }

 

   1:publicclass Detail
   2: {
   3:public Detail()
   4:     {
   5:this.Masters = new List<Master>();
   6:     }
   7:  
   8:public Int32 DetailId { get; set; }
   9:  
  10:publicvirtual ICollection<Master> Masters { get; protected set; }
  11: }

image

One-to-Many With Composite Key

In this case we have a composite primary key constituted by a foreign key and a scalar column: a Master instance is related with many Details and each Detail is identified by both a single Master and a timestamp.

   1:publicclass Master
   2: {
   3:public Master()
   4:     {
   5:this.Details = new List<Detail>();
   6:     }
   7:  
   8:public Int32 MasterId { get; set; }
   9:  
  10:publicvirtual ICollection<Detail> Details { get; protected set; }
  11: }

 

   1:publicclass Detail
   2: {
   3:     [Key]
   4:     [ForeignKey("Master")]
   5:     [Column(Order = 0)]
   6:public Int32 MasterId { get; set; }
   7:  
   8:     [Required]
   9:publicvirtual Master Master { get; set; }
  10:  
  11:     [Key]
  12:     [Column(Order = 1)]
  13:public DateTime Timestamp { get; set; }
  14: }

image

Have I forgotten something? Let me know!


Viewing all articles
Browse latest Browse all 404

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>