【问题标题】:Linq join with Many to ManyLinq 加入多对多
【发布时间】:2017-09-24 20:19:28
【问题描述】:

我正在使用 MVC、C# 和 EntityFramework。

我在多对多连接上看到了不同的解决方案,经过大量修改后,我让它在 Linqpad 中工作。但是当我在我的解决方案中尝试它时,我收到一个错误,因为其中一个表不在我的 DBContext 中。

我有两张可见的桌子和一张隐藏的桌子。物品、食谱和食谱物品。

所有食谱都基于一个项目并使用两个或多个项目来制作。 所以我想要一个列表,IEnumerable 或类似的列表,其中包含指定此食谱的 Items 和 Recipes 的数据,然后我想要制作食谱所需的所有项目。

以下查询在 LinqPad 中有效

var t = from r in Recipes
join i in Items on r.ItemId equals i.Id
select new {FinalProduct = r.FinalProduct, Effect= i.Effect, 
Description = r.Description, Ingredients = r.RecipeItems.Select(g => g.Item)};

当我在我的解决方案中执行此操作时,我收到错误,因为我的 DBContext 仅包含配方和项目,但没有配方项目。我猜 Entityframework 可以在没有我的情况下处理这个问题。

我尝试创建DbSet<RecipeItems>,但没有任何运气。你们中的任何人都对我如何前进有任何建议。

物品类别

  public class Item
  {
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Effect { get; set; }
    public bool Published { get; set; }

    public virtual ICollection<Recipe> Recipe { get; set; }
  }

食谱课

public class Recipe
  {
    [Key]
    public int Id { get; set; }
    public int ItemId { get; set; }

    [Display(Name = "Final Product")]
    public string FinalProduct { get; set; }
    public string Description { get; set; }
    public RecipeGroup RecipeGroup { get; set; }
    public bool Published { get; set; }

    public virtual ICollection<Item> Ingredients { get; set; }
  }

Recipe中的ItemId是设置Recipe实际制作的Item。

【问题讨论】:

  • 那么您必须将 ReceipeItems 引入上下文。但是你已经介绍了ItemsRecipes 你必须对RecipeItems 做同样的事情
  • @user12345 不,EF 可以处理隐藏的联结表。
  • 请显示课程,ItemRecipe。你有哪些导航属性?另外,您如何区分“基础”项目和其他项目?
  • @GertArnold 我编辑了帖子以添加课程,希望对您有所帮助。
  • @GertArnold 我没有意识到这一点,因为我并没有真正使用过 EF。我是否正确理解它允许加入上下文中未指定的表?这不会使所有类型的安全措施失效,还是我在这里遗漏了一些非常明显的东西?

标签: c# asp.net-mvc entity-framework linq


【解决方案1】:

尝试将此添加到您的食谱对象:

public Recipe()
{
        this.Ingredients = new HashSet<Item>();
}

这会覆盖该类的默认构造函数,并为 EF 提供一个初始化相关对象的位置。

【讨论】:

    猜你喜欢
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多