Question

i am trying to run LINQ query. I have 2 tables with many-to-many relationship and i break them into one-to-many relationship by introducing another table in between, holding primary keys of both table to ensure 3 normal form. now i have mapping class for both table in asp.net but not in between table... i been suggested in previous blog that i don't need to map in-between table and don't need to add that in dbContext-- DbSet either, if i understood correctly!

I want LINQ query where i get all the records from table-Y where table-X ID(PK) == 2... i am aware that can be done in sql query but struggling with LINQ ....

Many thanks in advanced...

mapping classes for 1:* relationship in Entityframework - ASP.NET MVC

enter image description here

Was it helpful?

Solution

Assume table-X holds posts and table-Y holds tags:

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

In this case EF will generate junction table TagPosts for you and query to get all posts which are linked with tags having Id equal to 2 will be:

var query = db.Posts.Where(p => p.Tags.Any(t => t.Id == 2));

Generated SQL query will look like

SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Title] AS [Title]
    FROM [dbo].[Posts] AS [Extent1]
    WHERE  EXISTS (SELECT
        1 AS [C1]
        FROM [dbo].[TagPosts] AS [Extent2]
        WHERE ([Extent1].[Id] = [Extent2].[Post_Id]) AND 
              (2 = [Extent2].[Tag_Id])
    )

As you can see, EF is smart enough to check ids in junction table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top