2017-09-24 89 views
1

我正在使用MVC,C#和EntityFramework。Linq加入多对多

我在多对多的连接上看到了不同的解决方案,经过很多修补之后,我在Linqpad中使用了它。但是,当我在我的解决方案中尝试它时,我得到一个错误,因为其中一个表不在我的DBContext中。

我有两个可见的表,一个隐藏。项目,食谱& RecipeItems。

所有食谱都基于一个项目,并使用两个或更多的项目。 所以我想要一个列表,IEnumerable或类似的数据来自两个项目和食谱,指定这个配方,然后我想要所有项目所需的配方。

下面的查询工作在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只包含配方和物品,但没有RecipeItems。我猜,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; } 
    } 

的项目Id的配方是设置实际商品的菜肴会令。

+0

好吧,你必须将ReceipeItems带入上下文。但是,您已经介绍了“Items”和“Recipes”,您必须对“RecipeItems”执行相同的操作。 – user12345

+0

@ user12345否,EF可以处理隐藏的联结表。 –

+1

请显示课程,“项目”,“食谱”。你有什么导航属性?另外,你如何区分“基本”项目和其他项目? –

回答

0

尝试添加该到你的食谱对象:

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

这将覆盖类的默认构造函数和那种给人EF初始化相关的对象的地方。