【发布时间】:2011-06-11 18:45:11
【问题描述】:
我想举一个简短的例子,说明您如何在 Entity Framework 4 Code-First CTP 5 中实际执行关系?
希望能举出这种关系的例子:
* one-to-many
* many-to-many
非常感谢!
【问题讨论】:
标签: asp.net entity-framework asp.net-mvc-3 code-first ef-code-first
我想举一个简短的例子,说明您如何在 Entity Framework 4 Code-First CTP 5 中实际执行关系?
希望能举出这种关系的例子:
* one-to-many
* many-to-many
非常感谢!
【问题讨论】:
标签: asp.net entity-framework asp.net-mvc-3 code-first ef-code-first
一对一
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 能够显示每个项目的发票详细信息以及产品本身的描述。
【讨论】: