假设我在Entity Framework,Library和Book中有两个表。这些是多对多的连接,在另一个名为Library_Book的表中,但它被隐藏,因为它是连接表。
如何通过查询连接表(实体框架中没有自己的类)来检查库是否有某本书,而不从连接表中返回库中所有书籍的列表,而是使用LINQ检查只有具有bookId和LibraryId的记录。
非常感谢提前。
答案 0 :(得分:1)
要确定已知图书馆是否有已知图书,您可以执行以下操作:
bool hasIt = (from l in Libraries from b in l.Books where b.Id == 5 where l.Id == 3
select l).Any();
此Linq查询不会触及Library或Books表。它看起来像这样:
SELECT
CASE WHEN ( EXISTS (SELECT
1 AS [C1]
FROM [dbo].[LibraryBookIntersection] AS [Extent1]
WHERE (5 = [Extent1].[BookId]) AND (3 = [Extent1].[LibraryId])
)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[LibraryBookIntersection] AS [Extent2]
WHERE (5 = [Extent2].[BookId]) AND (3 = [Extent2].[LibraryId])
)) THEN cast(0 as bit) END AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]