在常规SQL中,我可以编写类似
的查询 select * from geocodes where NAME='somename' and STATE='somestate'
但是在LINQ中,我不知道该怎么做。我想为使用LINQ的以下单个查询编写一些组合查询:
if (!String.IsNullOrEmpty(searchString))
{
switch (searchBy)
{
case "Name":
geocodes = geocodes.Where(s => s.NAME.Contains(searchString));
break;
case "Site":
geocodes = geocodes.Where(s => s.CFN_SITE.Contains(searchString));
break;
case "Address":
geocodes = geocodes.Where(s => s.STREET1.Contains(searchString));
break;
case "City":
geocodes = geocodes.Where(s => s.CITY.Contains(searchString));
break;
case "State":
geocodes = geocodes.Where(s => s.STATE_CODE.Contains(searchString));
break;
case "Acct":
geocodes = geocodes.Where(s => s.AccountNumber.Contains(searchString));
break;
}
}
答案 0 :(得分:3)
使用&&
逻辑AND运算符:
geoCodes = geoCodes.Where(s => s.Name.Contains(someName) && s.State.Contains(someState));
答案 1 :(得分:1)
如果geocodes
是IQueryable<>
,则可以利用创建可查询对象所附带的延迟执行。您的代码可能看起来像这样:
if(searchByName) //Some boolean value to indicate you are searching the name
{
geocodes = geocodes.Where(s => s.NAME.Contains(searchString));
}
if(searchBySite)
{
geocodes = geocodes.Where(s => s.CFN_SITE.Contains(searchString));
}
if(searchByAddress)
{
geocodes = geocodes.Where(s => s.STREET1.Contains(searchString));
}
//etc...
您的查询实际上不会发送到数据库,因为您纯粹是在构建它。仅当您通过枚举结果(通过调用ToList()
或仅对其进行循环)来实现数据时,实体框架才会构建所需的SQL