本文介绍了查询使用LINQ /实体框架一个多一对多的关系。 CodeFirst的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何查询使用实体框架代码优先和LINQ一个多一对多的关系?问题是,EF自动创建的关系表。所以,我没有在我的背景

How can I query a many-to-many relationship using Entity Framework code first and linq? The problem is that EF create automatically the relation table. So, I don't have it in my context.

这是关系模型:

我需要为文章的列表具体CATEGORY_ID,基本上复制这样的事情:

I need a list of Articles for a specific Category_Id, basically replicate something like that:

select a.Id, a.Title,a.ShortDescription
from Articles a
join CategoryArticles ca on ca.Article_Id=a.Id
where ca.Category_Id  = @parameter

不过我的DbContext只有:

However my dbcontext only have :

public DbSet<Article> Articles { get; set; }
public DbSet<Category> Categories { get; set; }.



感谢您的帮助。

Thanks for any help.

推荐答案

您可以这样做:

var cat_id=1; // Change this variable for your real cat_id

var query= from article in db.Articles
           where article.Categories.Any(c=>c.Category_ID==cat_id)
           select article;



这样你会得到一个满足您需要的条件的条款。这是由该查询生成的SQL代码:

This way you will get the articles that satisfies the condition you want. This is the sql code that is generated by that query:

    SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Title] AS [Title]
    FROM [dbo].[Articles] AS [Extent1]
    WHERE  EXISTS (SELECT
        1 AS [C1]
        FROM [dbo].[ArticleCategories] AS [Extent2]
        WHERE ([Extent1].[Id] = [Extent2].[Article_Id]) AND ([Extent2].[Category_Id] = @p__linq__0))

这篇关于查询使用LINQ /实体框架一个多一对多的关系。 CodeFirst的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:06