【问题标题】:Entity Framework Code First - Interfaces实体框架代码优先 - 接口
【发布时间】:2013-07-24 08:28:09
【问题描述】:

我想为餐厅制作应用程序。这是关于计算配方的。

我有域类: - 成分 - 食谱 - 食谱项目

Recipe 有RecipeItem 列表。

RecipeItem 可以是成分,也可以是食谱。

所以我正在使用具有 2 个属性(Id、Name)的接口 IItem。 如果我在课堂上使用接口,数据库生成器会忽略此字段。

在这里查看我的课程:

public class Ingredient : IItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }

public class Recipe : IItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<RecipeItem> RecipeItems { get; set; }
    }

public class RecipeItem
    {
        public int Id { get; set; }
        public IItem Item { get; set; }
        public double Quantity { get; set; }
    }

CodeFirst 自动为我生成带有上述表格的数据库。

我希望数据库表 RecipeItem 看起来像:

> Id 
> Quantity 
> Recipe_Id - FK of Recipe ID 
> RecipePointer - Nullable FK of specific Recipe
> IngredientPointer - Nullable FK of specific Ingredient

但只有:

> Id 
> Quantity 
> Recipe_Id - FK of Recipe ID 

如果我将例如成分放入 RecipeItem,则成分的 ID 将插入到成分指针中。

我想使用 FLUENT API 进行映射,但我不知道如何。

我不知道我想要的是否可能,或者是否有更好的方法来解决我的问题。

我已经在 Pluralsight 上观看了 CodeFirst 视频,并在论坛中浏览,但找不到答案。

感谢您的帮助。

【问题讨论】:

    标签: c# entity-framework interface ef-code-first code-first


    【解决方案1】:

    不确定是否可以,但如果可以,不要使用接口而是使用类,请尝试

    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class Ingredient : Item
    {
        public double Price { get; set; }
    }
    
    public class Recipe : Item
    {
        public List<RecipeItem> RecipeItems { get; set; }
    }
    
    public class RecipeItem
    {
        public int Id { get; set; }
        public Item Item { get; set; }
        public double Quantity { get; set; }
    }
    

    那么你可能想了解EF and TPH

    【讨论】:

      【解决方案2】:

      您需要使用 DataAnnotations 来为 EF 阐明如何生成 DB Generation Script

      对于您的解决方案,我可以建议您

      使用 InversProperty 和 ForeignKey 属性

      看看以下资源:

      https://msdn.microsoft.com/en-us/data/jj193542.aspx

      https://msdn.microsoft.com/en-us/data/gg193958.aspx

      【讨论】:

        猜你喜欢
        • 2015-04-09
        • 1970-01-01
        • 1970-01-01
        • 2012-03-03
        • 1970-01-01
        • 2017-09-01
        • 2014-05-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多