实体框架代码优先 - 接口

时间:2013-07-24 08:28:10

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

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

我有域类: - 成分 - 食谱 - RecipeItem

Recipe有RecipeItem列表。

RecipeItem可能是成分,但也可能是食谱。

所以我使用Interface IItem有2个属性(Id,Name)。 如果我在我的类中使用Interface,db生成器会忽略该字段。

在这里查看我的课程:

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放入例如Ingredient,则会将成分Id添加到IngredientPointer中。

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

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

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

您需要使用DataAnnotations为EF阐明如何生成数据库生成脚本

为你的解决方案,我可以建议你

使用InversProperty和ForeignKey属性

查看以下资源:

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

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