How do you actually perform relationships in Entity Framework 4 Code-First CTP 5?

前端 未结 1 1755
死守一世寂寞
死守一世寂寞 2020-12-28 23:51

I would like to have a short example on how do you actually perform relationships in Entity Framework 4 Code-First CTP 5 ?

Would love an example for these kind of re

1条回答
  •  隐瞒了意图╮
    2020-12-29 00:10

    One to One

    public class One
    {
      public int Id {get;set;}
      public virtual Two RelationTwo {get;set;}
    }
    
    public class Two
    {
     public int Id {get;set;}
     public virtual One RelationOne {get;set;}
    }
    

    Things to note, it has to be virtual

    One to Many

    public class One
    {
      public int Id {get;set;}
      public virtual ICollection RelationTwo {get;set;}
    }
    
    public class Two
    {
     public int Id {get;set;}
     public virtual One RelationOne {get;set;}
    }
    

    Many to Many

    public class One
    {
      public int Id {get;set;}
      public virtual ICollection RelationTwo {get;set;}
    }
    
    public class Two
    {
     public int Id {get;set;}
     public virtual ICollection RelationOne {get;set;}
    }
    

    note that it needs to be ICollection

    Following links maybe helpful, click and click

    Hope this helps.

    EDIT

    Updated to include one to many.

    EDIT #2

    Updated to include a potential for doing the Invoice <-> Product scenario which was requested by comment.

    note: this is untested, but should put you in the right direction

    public class Invoice
    {
        public int Id {get;set;}
        //.. etc. other details on invoice, linking to shipping address etc.
    
        public virtual ICollection Items {get;set;}
    }
    
    public class InvoiceProduct
    {
        public int Id {get;set;}
        public int Quantity {get;set;}
        public decimal Price {get;set;} // possibly calculated
        //.. other details such as discounts maybe
    
        public virtual Product Product {get;set;}
        public virtual Invoice Order {get;set;} // maybe but not required
    }
    
    public class Product
    {
        public int Id {get;set;}
        //.. other details about product
    }
    

    Using this you could then iterate through all the items on the invoice and then foreach be able to show the invoice details about each item as well as a description from the product itself.

    0 讨论(0)
提交回复
热议问题