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

不问归期 提交于 2019-12-18 11:35:21

问题


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 relations :

* one-to-many
* many-to-many

Thanks a lots!


回答1:


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<Two> 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<Two> RelationTwo {get;set;}
}

public class Two
{
 public int Id {get;set;}
 public virtual ICollection<One> 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<InvoiceProduct> 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.



来源:https://stackoverflow.com/questions/4735981/how-do-you-actually-perform-relationships-in-entity-framework-4-code-first-ctp-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!