7
我想就如何真正在Entity Framework 4 Code-First CTP 5中执行关系做一个简短的例子?您如何在Entity Framework 4 Code-First CTP 5中真正执行关系?
会爱一个例子,这些类型的关系:
* one-to-many
* many-to-many
感谢很多!
我想就如何真正在Entity Framework 4 Code-First CTP 5中执行关系做一个简短的例子?您如何在Entity Framework 4 Code-First CTP 5中真正执行关系?
会爱一个例子,这些类型的关系:
* 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;}
}
需要注意的事项,它必须是虚拟
一对多
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能够显示发票明细关于每件商品以及产品本身的描述。
我不相信他们需要虚拟(但我强烈建议让他们虚拟)。如果它们未被标记为虚拟,则该关系将仍然存在,但是EF不会使用延迟加载,并且只会在对应实体已加载到会话中时才加载关系的另一侧。此外,对于一对多,如何做到这一点可以通过您的答案来推断,并不需要双方的参考,尽管它可能对应用程序的需求有所帮助。 – 2011-01-19 14:06:54