LINQ-to-Entity内部使用上下文来处理连接? [英] How does .Net handle the connection in LINQ-To-Entity inside using context?

查看:82
本文介绍了LINQ-to-Entity内部使用上下文来处理连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用了Linq-To-Entity。但是,在某些情况下,我犹豫使用存储过程 LINQ to Table或View 。但是,我通常更喜欢使用LINQ,因为 语法。我搜索过谷歌,但没有找到我的问题的详细信息。



我们来考虑一下这个代码:

  using(NorthwindEntities db = new NorthwindEntities())
{
var custs = from c in db.Customers where c.City ==Londonselect c;
var edus = from c in db.Educations其中c.Education!=2select c;
// ...等等
}

问题

1.是否为每个查询打开一个新的连接?如果是这样,那么不建议单独使用上述查询?

2.此外,你能否建议我有什么情况我必须使用存储过程而不是LINQ?

解决方案


是否为每个查询打开一个新的连接?


p>

根据文档


当调用查询方法时,将打开连接,并保持打开状态直到ObjectResult已被完全消耗或处理。


但是,.NET的连接是,所以相同的连接对象将被重用(如果需要,我假设重新打开)。



请注意,查询不执行 c c c $ c $, code>,单个首先等)。在这之前,这只是一个查询。这意味着你必须在上下文被排除之前使用查询执行某些,否则你会得到例外。


有什么情况下我必须使用存储过程而不是LINQ吗?


如果查询太复杂,无法使用Linq构建,那么存储过程就是一个合理的选择。


I am using Linq-To-Entity in my project. But, I am hesitating to use Stored Procedure or LINQ to Table or View in some situations. But, I generally prefer to use LINQ, because of the pleasent syntax. I have searched google, but not found detailed asnwer to my question.

Let's consider this code:

using (NorthwindEntities db = new NorthwindEntities())
{
    var custs = from c in db.Customers where c.City == "London" select c;
    var edus = from c in db.Educations where c.Education != "2" select c;
    // ... and so on
}

Questions:
1. Does it open a new connection for each query? If it does, then it is not adviced to use above queries seperately?
2. Also, could you advice me is there any situations that I must use Stored Procedure instead of LINQ?

解决方案

Does it open a new connection for each query?

Sort of.

According to the documentation

When a query method is called, the connection is opened, and it remains open until the ObjectResult has been completely consumed or disposed.

However, connections are pooled by .NET, so the same connection object will be reused (and I assume re-opened if necessary).

Note that a query is not executed until you enumerate over it (using foreach, ToList, ToArray, Single, First, etc.). Until then it's just a query. What that means is you must do something with the query before the context is disposed, or you'll get an exception.

Are there any situations where I must use Stored Procedure instead of LINQ?

If your queries are too complex to be constructed using Linq, then a stored procedure is a reasonable alternative.

这篇关于LINQ-to-Entity内部使用上下文来处理连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆