7

我想举一个简短的例子,说明您如何在 Entity Framework 4 Code-First CTP 5 中实际执行关系?

会喜欢这种关系的一个例子:

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

十分感谢!

4

1 回答 1

10

一对一

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

需要注意的是,它必须是虚拟的

一对多

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

以下链接可能会有所帮助,请单击单击

希望这可以帮助。

编辑

更新为包括一对多。

编辑#2

更新以包括执行评论要求的发票 <-> 产品方案的可能性。

注意:这是未经测试的,但应该让你朝着正确的方向前进

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 能够显示每个项目的发票详细信息以及产品本身的描述。

于 2011-01-19T13:59:18.900 回答