简体   繁体   English

LINQ to Entities 查询多对多表

[英]LINQ to Entities querying a many to many table

I am trying to implement some filtering functionality from a many to many table where a user filters on one or more tags.我正在尝试从多对多表中实现一些过滤功能,其中用户过滤一个或多个标签。 I currently have the following query (simplified from the version I'm working with):我目前有以下查询(从我正在使用的版本简化):

var query = from adm in admissionContext.SampleTable
        from tag in admissionContext.SampleTags.Where(t => t.SampleID == adm.ID).DefaultIfEmpty()
        from tagItem in admissionContext.SampleTagElements.Where(i => i.ID == tag.ElementID).DefaultIfEmpty()
        where searchFilter.TagIDs.Count == 0 || searchFilter.TagIDs.Contains(tag.ElementID)
        select new SampleInfo
        {
            ID = adm.ID,
            ReferralTags = tagItem != null ? tagItem.TagText : string.Empty,
        };

The filtering works fine, and there is additional logic that groups the result by their SampleTableID to merge the results together, but if there are multiple tags against a SampleTable record, only one (the result from the Contains check) is retrieved and displayed in the UI, but I want it to return all related SampleTags under the same SampleID as well.过滤工作正常,并且有额外的逻辑按 SampleTableID 对结果进行分组以将结果合并在一起,但如果针对 SampleTable 记录有多个标签,则仅检索一个(包含检查的结果)并显示在UI,但我希望它也返回相同 SampleID 下的所有相关 SampleTag。 but I'm not sure what the LINQ to entities syntax is to go about doing this.但我不确定 LINQ to entity 语法是用来做什么的。

This is part of a larger query so ideally I need to stick with LINQ to entities.这是更大查询的一部分,所以理想情况下我需要坚持使用 LINQ to entity。

Seems like you are joining 3 tables, here is 2 approaches -好像您要加入 3 个表,这里有 2 种方法-

  1. You can join your tables by join keyword, then use GroupBy() on that.您可以通过 join 关键字加入您的表,然后在其上使用 GroupBy() 。
  2. You can do by passing column values as primary key into other tables foreign key in dictionary form and then apply join.您可以通过将列值作为主键以字典形式传递给其他表的外键,然后应用连接来完成。

Hope that works fine to you.希望这对你有用。

**Suggestion - Please try to avoid complex query linq is slow than lambda expressions. **建议 - 请尽量避免复杂的查询 linq 比 lambda 表达式慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM