开发者

Interrogating a many to many table in the entity framework

开发者 https://www.devze.com 2023-01-26 03:59 出处:网络
Say I have two tables in the Entity Framework, Library and Book. These are on a many to many join with another table inbetween called Library_Book but it is hidden as it is the join table.

Say I have two tables in the Entity Framework, Library and Book. These are on a many to many join with another table inbetween called Library_Book but it is hidden as it is the join table.

How would I check using LINQ whether a library had a certain book by i开发者_JS百科nterrogating the join table (which doesnt have its own class in the Entity Framework) without returning the list of all the books in a library from the join table but instead only the record which has the bookId and the LibraryId.

Many thanks in advance.


To determine if known library has a known book, you could do something like this:

bool hasIt = (from l in Libraries from b in l.Books where b.Id == 5 where l.Id == 3 
select l).Any();

This Linq query will not touch either the Library or Books table. It will look like this:

    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]
0

精彩评论

暂无评论...
验证码 换一张
取 消