实体框架ASP.NET MVC中的配方成分数据库
本文关键字:方成 数据库 框架 ASP NET MVC 实体 | 更新日期: 2023-09-27 18:24:11
这将创建两个表"Ingredient"answers"Recipe",以及一个用于多对多映射的附加表。
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; }
}
问题:我想在实体框架将创建的第三个映射表中包括额外的列"数量"。如何使之成为可能?提前谢谢。
当您获得一些额外信息时,我怀疑它不再真正算作映射表了——它不仅仅是多对多映射。我认为你应该把它建模为另一张表:
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));