lin*_*nkb 6 c# linq asp.net lambda
我有两个数据库表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;
Run Code Online (Sandbox Code Playgroud)
使用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);
Run Code Online (Sandbox Code Playgroud)
所以,我知道如何做到这一点,如果重点是一次选择所有这一切,不幸的是,事实并非如此.我正在根据用户输入构建查询,因此我不知道所有选择.
所以这就是我的代码:
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 ...........?);
Run Code Online (Sandbox Code Playgroud)
与两个where语句的区别在于,对于第一个语句,每个联系人只有一个名称,但后者的联系人可以包含多个操作位置......
我已经设法找到一个解决方案,但是这个解决方案给了我一个不需要的对象,它包含两个表.我不知道如何处理它.
query.Join(_ctx.ContactOperationPlaces, c => c.Id, cop => cop.ContactId,
(c, cop) => new {c, cop}).Where(o => o.cop.municipalityId == 301);
Run Code Online (Sandbox Code Playgroud)
从该表达式返回的对象是System.Linq.Iqueryable <{c:Contact,cop:ContactOperationalPlace}>,它不能转换为Contacts ...
那就是问题所在.答案可能很简单,但我找不到它......
Ufu*_*arı 13
在where子句之前创建一个包含两个对象的匿名类型,并在ContactOperationPlaces值上对其进行过滤.您只需在此之后选择联系人.
query.Join(_ctx.ContactOperationPlaces, c => c.Id, cop => cop.ContactId,
(c, cop) => new {c, cop}).Where(o => o.cop.municipalityId == 301)
.Select(o => o.c)
.Distinct();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23864 次 |
| 最近记录: |