我试图将我已编写的SQL查询转换为等效的Linq-To-Entities查询。它有一个子查询,将几个字段连接在一起,然后将其用作我需要加入的字段。
SQL:
select distinct ta.Filename
from TableA ta
inner join (
SELECT distinct isnull(tb.StringField,convert(varchar,tc.IntField) + convert(varchar,tb.IntFieldB)) as NewNames
FROM TableB tb
inner join TableC tc
on tb.fkC = tc.ID
) tj
on tj.NewNames = ta.Filename
这是我目前看到Linq查询的内容,但我知道它不正确。
LINQ:
var query = (from ta in ef.TableA
where (from tb in ef.TableB
from tc in ef.TableC
.Where(tc => tc.ID == tb.fkC)
select new { NewNames = tb.StringField ?? SqlFunctions.StringConvert((double)tc.IntField) + SqlFunctions.StringConvert((double)tb.IntField2)}
).Contains(ta.Filename)
select ta.Filename
).Distinct().OrderBy(ta => ta.Filename).ToList();
由于子查询中创建的匿名类型,它抱怨Contains
。这样做的正确方法是什么?
答案 0 :(得分:1)
您可以尝试Any
扩展方法:
var query = (from ta in ef.TableA
where (from tb in ef.TableB
from tc in ef.TableC
.Where(tc => tc.ID == tb.fkC)
select new { NewNames = tb.StringField ?? SqlFunctions.StringConvert((double)tc.IntField) + SqlFunctions.StringConvert((double)tb.IntField2)}
).Any(e.NewNames==ta.Filename)
select ta.Filename
).Distinct().OrderBy(ta => ta.Filename).ToList();
或者您可以使用在连接操作后获得的字符串来预测内部查询:
var query = (from ta in ef.TableA
where (from tb in ef.TableB
from tc in ef.TableC
.Where(tc => tc.ID == tb.fkC)
select (tb.StringField ?? SqlFunctions.StringConvert((double)tc.IntField) + SqlFunctions.StringConvert((double)tb.IntField2))
).Contains(ta.Filename)
select ta.Filename
).Distinct().OrderBy(ta => ta.Filename).ToList();
我认为以下内容可以改善您的查询:
var query = (from ta in ef.TableA
where (from tb in ef.TableB
join tc in ef.TableC on tb.fkC equals tc.Id
where (tb.StringField ?? SqlFunctions.StringConvert((double)tc.IntField) + SqlFunctions.StringConvert((double)tb.IntField2))==ta.Filename
select tb).Any()
select ta.Filename
).Distinct().OrderBy(ta => ta.Filename).ToList();