[英]How to avoid multiple queries one complex objects in EF .net core
In .net core 2.2 I have a model likes this: 在.net core 2.2我有一个模特喜欢这个:
public class A
{
public ICollection<B> B { get; set; }
}
public class B
{
public ICollection<C> C { get; set; }
public ICollection<D> D { get; set; }
}
public class C
{
}
public class D
{
}
And the query is something like this: 查询是这样的:
var query = from record in Set<A>()
where record.Id == Id
select new AProjection
{
BProjection =( from bRecord in Set<B>()
where bRecord.Id = record.BId
select new BProjection
{
CProjection = bRecord.C.Select( b => new CProjection {/* data here */ }),
DProjection = bRecord.C.Select( b => new DProjection {/* data here */ })
})
}
I want to return the data into a projection, but for each object of Type B is making a query to get the objects Type C and another to get the objects Type D. How can I avoid this behaviour? 我想将数据返回到投影中,但是对于类型B的每个对象,进行查询以获取对象类型C而另一个对象获取对象类型D.如何避免此行为?
It's the typical N+1 queries problem addressed in this question: 这是此问题中解决的典型N + 1查询问题:
How to avoid n+1 queries in EF Core 2.1? 如何避免EF Core 2.1中的n + 1个查询?
EF Core 2.1 has introduced Optimization of correlated subqueries , but as mentioned in the linked documentation, you need to opt-in for it by adding ToList()
to all collection projections. EF Core 2.1引入了相关子查询的优化 ,但是如链接文档中所述,您需要通过向所有集合投影添加
ToList()
来选择加入它。
Also use navigation properties instead of manual joins where possible. 也尽可能使用导航属性而不是手动连接。
eg 例如
var query =
from a in db.Set<A>()
select new AProjection
{
B = (from b in a.B
select new BProjection
{
C = (from c in b.C select new CProjection { ... }).ToList(), // <--
D = (from d in b.D select new DProjection { ... }).ToList(), // <--
}).ToList() // <--
};
This will execute total 4 SQL queries - one for each projection. 这将执行总共4个SQL查询 - 每个投影一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.