我正在尝试将包含存在子查询的sql语句转换为linq lambda表达式查询,但是如果子查询为DbSet,则预期的SQL事件探查器sql会忽略我的子查询。
我已经尝试使用int列表来生成子查询,该列表会生成和Where IN子句sql,但是一旦我使用DbSet放置了子查询,该子查询就会被忽略。
var ids = new List<int>(){ 1, 2, 3, 4, 5 };
using(var db = new MyDbContext(dbContextOptions))
{
var query = db.Query<VwSomeView>()
.Where(v => ids.Any(i => i == v.Id) &&
v.Property1 == "Y");
var results = query.ToList();
}
这会产生
SELECT v.Property1, v.Property2, v.Property3
FROM VwSomeView as v
WHERE v.Id IN (1, 2, 3, 4, 5) AND v.Property1 = 'Y'
using(var db = new MyDbContext(dbContextOptions))
{
var query = db.Query<VwSomeView>()
.Where(v => ids.Any(i => i == v.Id) &&
( (v.Property1 == "Y") ||
(db.SomeDbSet.Any(s => s.Id == v.Id && s.Prop2 == v.Property2
&& s.Prop3 == "ConstantValue"))
);
var results = query.ToList();
}
产生:
SELECT v.Property1, v.Property2, v.Property3
FROM VwSomeView as v
在SQL事件探查器中
然后引发异常,调用ToList()时,对象引用未设置为Object的实例。
我期望生成的sql是
SELECT v.Property1, v.Property2, v.Property3
FROM VwSomeView as v
WHERE v.Id IN (1, 2, 3, 4, 5) &&
(
(v.Property1 = 'Y') ||
(Exists (SELECT * FROM SomeDbSet As s WHERE s.Id = v.Id && s.Prop2 = v.Property2 && s.Prop3 = "ConstantValue"))
)