带有存储过程和 IQueryable 的 LINQ (L2E)
考虑一个正常的 Linq 表达式将是这样的:
(这只是一个使事情更容易理解的示例)
IQueryable<Person> personQuery= (from ppl in PersonContext
select ppl).ASQueryable();
List<Person>personList = personQuery.where(x => x.age==13).ToList();
因此,如果我决定将 linq 查询的第一部分放入存储过程中,
事情会像这样发展。
IQueryable<Person> personQuery= PersonContext.sp_RetrievePerson().ASQueryable();
List<Person> personList = personQuery.where(x => x.age==13).ToList();
所以对于这个问题,我相信第一个方法仅在调用 toList() 时发送 sql 调用。
换句话说,发送到sql执行的查询将是
Select * from Person where age=13
但是对于方法2,这个查询将被发送执行多少次?
如果只发送 1 次,那么调用存储过程是否会变得多余,因为存储过程以执行速度更快而闻名,发送到 sql 的查询会是什么样子?
Consider a normal Linq expression will be something like this:
(This is just a sample to make things more understandable)
IQueryable<Person> personQuery= (from ppl in PersonContext
select ppl).ASQueryable();
List<Person>personList = personQuery.where(x => x.age==13).ToList();
So if I decided to put the 1st part of the linq query inside a stored procedure,
things will work out something like this.
IQueryable<Person> personQuery= PersonContext.sp_RetrievePerson().ASQueryable();
List<Person> personList = personQuery.where(x => x.age==13).ToList();
So for the question, I believe that the 1st method only sends the sql call when toList() is called.
In another words, the query sent to sql for execution will be
Select * from Person where age=13
But for method 2, how many times will this query be sent for execution?
If it is only sent 1 time, does it make it redundant to call the stored procedure as stored procedure is known for having a faster execution and how will the query sent to sql look like?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对此不太确定,但
PersonContext.sp_RetrievePerson()
返回一个ObjectResult
,它在内部使用 DbDataReader。这意味着存储过程被调用一次,personQuery.where(x => x.age==13)
迭代结果行并过滤掉不匹配的对象。通过为此使用存储过程,您可能会在查询数据库时获得较小的性能提升,但您必须在从数据库读取 Person 表中的每个对象后对其进行评估。因此,我认为在这种情况下,如果您向存储过程提供参数
age
来过滤数据库中已有的结果,那么使用存储过程才有意义。I am not sure about this one, but
PersonContext.sp_RetrievePerson()
returns anObjectResult
, which internally uses a DbDataReader. That means that the stored procedure is called once, thepersonQuery.where(x => x.age==13)
iterates over the resulting rows and filters out not matching objects.By using stored procedures for this you might get a small performance gain on querying the database, but you have to evaluate each object in the persons table, AFTER reading it from the database. So I think in this scenario using stored procedures only makes sense, if you provide a parameter
age
to the stored procedure for filtering the results already in the database.