【问题标题】:How do you actually perform relationships in Entity Framework 4 Code-First CTP 5?您如何在 Entity Framework 4 Code-First CTP 5 中实际执行关系?
【发布时间】: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


    【解决方案1】:

    一对一

    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

    以下链接可能会有所帮助,clickclick

    希望这会有所帮助。

    编辑

    更新为包含一对多。

    编辑#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 不会使用延迟加载,并且只会在相应实体已加载到会话中时才加载关系的另一端。此外,对于一对多,可以通过您的答案推断出如何做到这一点,不需要双方都参考,尽管根据应用程序的需求可能是有意义的。
    • 只是您感兴趣的另一个链接,我发现它是一个相当有用的代码先介绍:weblogs.asp.net/scottgu/archive/2010/07/16/…
    • 感谢您到目前为止的回答。还有一件事。如果它在您的发票有项目行的账单上下文中。这将涉及一个关系表。您如何处理这种情况?
    • 已更新以将 1 添加到多个 - @Rushino 你能扩展你上面提到的场景吗?
    • 好的。我会将您置于计费环境中。您有一张发票(第一个实体)。发票包括产品(第二实体),但发票上有包含您购买的产品数量的行。显然有一个关系表,其中包括 IdLine、IdInvoice、IdProduct 和 Quantity。您如何使用 EF4 Code-First 完成此场景?
    猜你喜欢
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    相关资源
    最近更新 更多