2012-02-11 69 views
1

这将创建两个表“配料”和“配方”以及用于多对多映射的附加表。实体框架中的配方 - 配料数据库ASP.NET MVC

public class DC : DbContext { 
    public DbSet<Ingredient> Ingredients { get; set; } 
    public DbSet<Recipe> Recipes { get; set; } 
} 

public class Ingredient { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Recipe> Recipes { get; set; } 
} 

public class Recipe { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Ingredient> Ingredients { get; set; } 
} 

问题:我想在实体框架创建的第三个映射表中包含额外的列“数量”。如何做到这一点?提前致谢。

回答

3

当你有一些额外的信息,我怀疑它不会再算作一个映射表 - 它不是只是一个多对多的映射。我想你应该只是其建模为另一个表:

public class Ingredient { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<RecipePart> RecipeParts { get; set; } 
} 

public class RecipePart { 
    public int Id { get; set; } 
    public Ingredient { get; set; } 
    public Recipe { get; set; } 
    // You'll want to think what unit this is meant to be in... another field? 
    public decimal Quantity { get; set; } 
} 

public class Recipe { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<RecipePart> Parts { get; set; } 
} 

所以,现在你真的不有许多一对多映射 - 你有两个一般的多到一的映射。你是否一定需要在模型中暴露的“配料到配方”映射?如果你想找出所有使用特定配料的配方,你总是可以做一个查询,如:

var recipies = DB.Recipies.Where(r => r.Parts 
             .Any(p => p.Ingredient == ingredient)); 
+0

感谢您的帮助,但由于我是新来的实体框架,我有一个问题关于您提供的RecipePart类。应该是:“公共配料成分{get; set;};”或“公共int IngredientID {搞定;设置;}”? – Acute 2012-02-17 11:26:28

+0

@Acute:我不能说,我害怕 - 我自己对EF的了解不够。 – 2012-02-17 20:39:31