【发布时间】:2021-03-04 15:48:42
【问题描述】:
我有嵌套条件运算符 Linq 查询来获取记录。问题是我在每个条件数据库上编写了多个 select&join,命中时间太高而无法获取记录,我需要减少查询命中 db 的时间。
由于我是 Enity Framwork 的新手,所以我没有太多优化使用条件语句的方式。
var uniqID = 12;
var keyID = 439;
var result = (from t1 in Table1
where t1.uniqueID == uniqID && t1.column9 == keyID && t1.column11 == true
select new {
Data1 = t1.Column1,
Data2 = t1.Column2,
Data3 = t1.Column3 == true ? (from t2 in Table2
where t2.uniqueID == uniqID && t2.Id == t1.column10
select t2.Data4).FirstOrDefault() : (from t3 in Table3
join t4 in Table4 on new {
t3.uniqueID,
t3.coulmn6
}
equals new {
t4.uniqueID,
t4.coulmn6
}
where t3.uniqueID == uniqID && t3.keyID == t1.column10
select t4.Data4).FirstOrDefault(),
ReceiptNo = (from t3 in Table3
join t5 in Table5 on new {
t3.uniqueID,
t3.coulmn6
}
equals new {
t5.uniqueID,
t5.coulmn6
}
where t3.uniqueID == uniqID && t3.keyID == t1.column9
select t5.Data5).FirstOrDefault()
}).Dump();
这是一个类似的。像这样我必须添加几个(比如 4-5)更多的子查询以及上面的一个
【问题讨论】:
-
在 EF 中,您几乎不应该使用 JOIN。相反,您的实体应该具有导航属性,并且您的查询应该使用这些属性。 docs.microsoft.com/en-us/ef/ef6/fundamentals/relationships
标签: sql entity-framework linq linq-to-entities