包括不与联接实体一起使用 [英] Include not working with join entities
问题描述
例如,我有以下实体(多对多,我也删除了不必要的道具):
As example I have following entities (many-to-many, I also removed unnessecary props):
public class Buffet
{
public int Id {get; set;}
public string Name {get; set;}
}
public class Recipe
{
public int Id {get; set;}
public string Name {get; set;}
public int CategoryId {get; set;}
public virtual Category Category {get; set;}
}
public class Category
{
public int Id {get; set;}
public string Name {get; set;}
}
加入实体:
public class BuffetRecipe
{
public int BuffetId {get; set;}
public virtual Buffet Buffet {get; set;}
public int RecipeId {get; set;}
public virtual Recipe Recipe {get; set;}
}
我想获取属于特定自助餐的所有食谱,
I want to get all recipes that belong to a specific buffet and want include the recipe category.
public IList<Recipe> GetRecipes(int buffetId)
{
return _dbContext.BuffetRecipes
.Where(item => item.BuffetId == buffetId)
.Include(item => item.Recipe)
.ThenInclude(item => item.Category)
.Select(item => item.Recipe)
.ToList();
}
我得到的列表总是返回prop Category = null的食谱。
我没有找到使Include()与Select()一起使用的解决方案...
The list I get always returns Recipes with prop Category = null. I didn't find a solution to make the Include() work together with the Select()...
我在做什么错??
更新:
我可以通过这种方式使它工作……但是我的感觉说这不是一个好方法方式是因为我有2个ToList()调用...但是现在我的结果中包含类别:
I can make it work this way... but my feeling says this is not a good way because i have 2 ToList() calls... but now I have category included in my results:
public IList<Recipe> GetRecipes(int buffetId)
{
return _dbContext.BuffetRecipes
.Where(item => item.BuffetId == buffetId)
.Include(item => item.Recipe)
.ThenInclude(item => item.Category)
.ToList()
.Select(item => item.Recipe)
.ToList();
}
推荐答案
包含
仅在可以应用于查询的最终结果时才有效。
Include
is only effective if it can be applied to the end result of the query.
您可以对其进行更改进入...
You could change it into ...
return _dbContext.BuffetRecipes
.Where(item => item.BuffetId == buffetId)
.Select(item => item.Recipe)
.Include(rcp => rcp.Category)
.ToList()
...但是,这样做的缺点是您复制食谱
s(与有 BuffetRecipes
)。最好使用食谱
开始查询:
... but the drawback of this is that you duplicate your Recipe
s (as many as they have BuffetRecipes
). It's better to start the query with Recipe
:
return _dbContext.Recipes
.Where(rcp => rcp.BuffetRecipes.Any(br => br.BuffetId == buffetId))
.Include(rcp => rcp.Category)
.ToList();
您看到我随意添加了导航属性 Recipe.BuffetRecipes
。这对您的模型来说应该没什么问题(相反,我会说)。
You see that I took the liberty to add a navigation property Recipe.BuffetRecipes
. This shouldn't be any problem with your model (on the contrary, I'd say).
这篇关于包括不与联接实体一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!