你怎么竟在实体框架4 code-CTP首先进行5的关系? [英] How do you actually perform relationships in Entity Framework 4 Code-First CTP 5?

查看:115
本文介绍了你怎么竟在实体框架4 code-CTP首先进行5的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对你怎么实际执行关系的简短的例子实体框架4 code-CTP首5?

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

感谢很多!

推荐答案

一对一

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

一对多

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;}
}

多对多

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;}
}

注意,它需要的ICollection

note that it needs to be ICollection

以下链接也许有用,<一个href=\"http://stackoverflow.com/questions/3617910/entity-framework-4-$c$c-first-many-to-many-insert\">click和<一个href=\"http://blogs.msdn.com/b/efdesign/archive/2010/06/01/conventions-for-$c$c-first.aspx\">click

希望这有助于。

修改

更新,包括一对多。

编辑#2

更新以包括做发票℃的​​潜力; - >产品方案这是由意见要求

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

注:这是未经测试,而是应该把你在正确的方向

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
}

使用这个你可以再通过发票上的所有元素的,然后的foreach能够显示每个项目的发票详细信息以及从产品本身的描述。

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.

这篇关于你怎么竟在实体框架4 code-CTP首先进行5的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆