是否可以在asp.net中使用linq中的条件运算符?我尝试过这段代码,但它显示:
The name BusinessInstance and LocalityMaster1 is not in a scope on the left hand side of 'equal' Consider swaping the expression on either side of 'equals'.
我需要将结果作为BusinessName,(LocalityName / BusinessAddress),CityName。我的sql如下:
from BusinessInstanceInfoKeys in db.utblYPBusinessInstanceInfoKeys.Where(x=> x.BusinessName.Contains(term))
join CityMaster in db.utblCityMasters
on BusinessInstanceInfoKeys.CityID equals CityMaster.CityID
let Address = BusinessInstanceInfoKeys.LocalityID != null
? from LocalityMaster1 in db.utblLocalityMasters
join BusinessInstance in db.utblYPBusinessInstanceInfoKeys
on BusinessInstance.LocalityID equals LocalityMaster1.LocalityID
select new
{
LocalityMaster1.LocalityName
}
: BusinessInstanceInfoKeys.BusinessAddress
select new
{
LocalityName = BusinessInstanceInfoKeys.BusinessName + ",(" + Address + ")" + "," + CityMaster.CityName
};
有人能提出正确的建议吗?
答案 0 :(得分:1)
要消除错误,请将其替换为:
on BusinessInstance.LocalityID equals LocalityMaster1.LocalityID
用这个:
on LocalityMaster1.LocalityID equals BusinessInstance.LocalityID
此外,您可以在let
内包含三元表达式,但可能会出现几个问题:
如果您直接查询数据库(即实体框架),我不知道它能够从三元表达式生成有意义的SQL,因此它可能会抛出异常。
三元表达式中的两个条件都必须返回相同的数据类型。你的似乎没有。
根据您的评论,如果运行以下查询至少会返回一条记录,您可以尝试这样做。 (我假设 LocalityName
和 BusinessAddress
都是字符串。)
let Address = BusinessInstanceInfoKeys.LocalityID != null
? (from LocalityMaster1 in db.utblLocalityMasters
join BusinessInstance in db.utblYPBusinessInstanceInfoKeys
on BusinessInstance.LocalityID equals LocalityMaster1.LocalityID
select LocalityMaster1.LocalityName).FirstOrDefault()
: BusinessInstanceInfoKeys.BusinessAddress