簡體   English   中英

用實體框架無法訪問LINQ中的中間表?

[英]Can't access to middle table in LINQ with entity framework?

我在LINQ中執行查詢時遇到問題。 這是SQL中非常簡單的一個。

這是我的表格:

數據庫圖

這是我想要轉換為LINQ的查詢:

SELECT * FROM Recipe WHERE IDRecipe IN ( 
                    SELECT IDRecipe FROM RecipeTag 
                        INNER JOIN Tag ON Tag.IDTag = RecipeTag.IDTag  
                    WHERE Name LIKE '%{0}%') 

這是我嘗試過的,但問題是奇怪的是,RecipeTag表在上下文中不存在。 這似乎是在食譜中,但當我做db.Recipes.RecipeTag它不存在...

var recipeTag = from rt in db.RecipeTag
                join tg in db.Tags on rt.IDTag equals tg.IDTag
                where tg.Name.Contains(str)
                select rt.IDRecipe;

IEnumerable<Recipe> recipesTemp3 = (from recipe in db.Recipes
                                    where recipeTag.Contains(recipe.IDRecipe)
                                    select recipe).ToList();

我完全是LINQ的新手,很抱歉,如果這是一個非常基本的問題,但我找不到任何答案!

謝謝

LINQ將多對多關系轉換為每個外部表上的集合屬性。
你根本不需要中間表。

代替,

from recipe in db.Recipes
where recipe.RecipeTags.Any(t => t.Name.Contains(str))
select recipe

或者,更簡單:

from tag in db.RecipeTags
where tag.Name.Contains(str)
from recipe in tag.Recipes
select recipe
var recipes = db.Recipes.Where(r=>r.RecipeTag.Any(t=>t.Tag.Name.Contains("whatever")).ToList();

如果我理解你想要:

var recipeTags = db.RecipeTags.Where(p => p.Tag.Name.Contains(str)).Select(p => p.Recipe).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM