您如何在Entity Framework 4 Code-First CTP 5中实际执行关系?

Rus*_*ino 7 asp.net entity-framework code-first ef-code-first asp.net-mvc-3

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

会喜欢这种关系的榜样:

* one-to-many
* many-to-many
Run Code Online (Sandbox Code Playgroud)

十分感谢!

Wes*_*olf 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;}
}
Run Code Online (Sandbox Code Playgroud)

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

一对多

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;}
}
Run Code Online (Sandbox Code Playgroud)

多对多

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;}
}
Run Code Online (Sandbox Code Playgroud)

请注意,它需要是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
}
Run Code Online (Sandbox Code Playgroud)

使用此功能,您可以遍历发票上的所有项目,然后可以显示每个项目的发票详细信息以及产品本身的说明.

  • 我不认为他们需要虚拟(但我强烈建议他们虚拟).如果它们未标记为虚拟,则该关系仍将存在,但EF将不使用延迟加载,并且仅在相应实体已加载到会话中时才加载关系的另一侧.此外,对于一对多,如何做到这一点可以通过你的答案来推断,不需要双方的参考,尽管它可能有助于了解应用程序的需求. (2认同)