【发布时间】:2012-01-21 20:05:23
【问题描述】:
我有两个数据库表 Contact (Id, Name, ...) 和 ContactOperationalPlaces (ContactId, MunicipalityId),其中一个联系人可以连接到多个 ContactOperationalPlaces。
我要做的是使用 IQueryable 构建一个查询(ASP .NET、C#),它只选择存在于 ContactOperationalPlaces 表中的所有联系人,以及给定的 MunicipalityId。
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,不能强制转换为 Contacts...
所以,这就是问题所在。答案可能很简单,但就是找不到……
【问题讨论】: