Entity Framework Code First - 接口

3

我希望制作一款餐厅配方计算的应用程序。

我有以下域类: - Ingredient(原料) - Recipe(食谱) - RecipeItem(食谱项)

食谱包含一个RecipeItem列表。

RecipeItem既可以是Ingredient也可以是Recipe。

因此,我使用了IItem接口,其中包含两个属性(Id,Name)。 如果在我的类中使用接口,则数据库生成器会忽略此字段。

请查看我的类:

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 

如果我将Ingredient放入RecipeItem中,那么Ingredient的Id将被插入到IngredientPointer中。
我想使用FLUENT API进行映射,但我不知道如何操作。
我不知道我想要的是否可能实现,或者是否有更好的方法来解决我的问题。
我已经在Pluralsight上观看了CodeFirst视频,并在论坛中浏览了,但我找不到答案。
感谢您的任何帮助。
2个回答

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和TPH的内容。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接