加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在linq join(lambda)上添加where子句?

发布时间:2020-12-15 04:18:10 所属栏目:百科 来源:网络整理
导读:我有两个数据库表Contact(Id,Name,…)和ContactOperationalPlaces(ContactId,MunicipalityId),其中一个联系人可以连接到几个ContactOperationalPlaces. 我想要做的是使用IQueryable构建一个查询(ASP .NET,C#),它只选择具有给定MunicipalityId的ContactOperat
我有两个数据库表Contact(Id,Name,…)和ContactOperationalPlaces(ContactId,MunicipalityId),其中一个联系人可以连接到几个ContactOperationalPlaces.

我想要做的是使用IQueryable构建一个查询(ASP .NET,C#),它只选择具有给定MunicipalityId的ContactOperationalPlaces表中存在的所有联系人.

sql查询如下所示:

select * from Contacts c 
right join ContactOperationPlaces cop on c.Id = cop.ContactId 
where cop.MunicipalityId = 301;

使用linq它看起来像这样:

//_ctx is the context
var tmp = (from c in _ctx.Contacts
             join cop in _ctx.ContactOperationPlaces on c.Id equals cop.ContactId
             where cop.MunicipalityId == 301
             select c);

所以,我知道如何做到这一点,如果重点是一次选择所有这一切,不幸的是,事实并非如此.我正在根据用户输入构建查询,因此我不知道所有选择.

所以这就是我的代码:

IQueryable<Contacts> query = (from c in _ctx.Contacts select c);
//Some other logic....
/*Gets a partial name (string nameStr),and filters the contacts 
 so that only those with a match on names are selected*/
query = query.Where(c => c.Name.Contains(nameStr);
//Some more logic
//Gets the municipalityId and wants to filter on it! :( how to?
query = query.where(c => c.ContactOperationalPlaces ...........?);

与两个where语句的区别在于,对于第一个语句,每个联系人只有一个名称,但后者的联系人可以包含多个操作位置……

我已经设法找到一个解决方案,但是这个解决方案给了我一个不需要的对象,它包含两个表.我不知道如何处理它.

query.Join(_ctx.ContactOperationPlaces,c => c.Id,cop => cop.ContactId,(c,cop) => new {c,cop}).Where(o => o.cop.municipalityId == 301);

从此表达式返回的对象是System.Linq.Iqueryable< {c:Contact,cop:ContactOperationalPlace}>,并且无法强制转换为Contacts …

那就是问题所在.答案可能很简单,但我找不到它……

解决方法

在where子句之前创建一个包含两个对象的匿名类型,并在ContactOperationPlaces值上对其进行过滤.您只需在此之后选择联系人.
query.Join(_ctx.ContactOperationPlaces,cop}).Where(o => o.cop.municipalityId == 301)
                                    .Select(o => o.c)
                                    .Distinct();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读