我在我的项目中使用 Linq-To-Entity。但是,在某些情况下,我对使用 Stored Procedure
或 LINQ to Table or View
犹豫不决。但是,我通常更喜欢使用 LINQ,因为 pleasent 语法。我搜索了谷歌,但没有找到我的问题的详细答案。
让我们考虑一下这段代码:
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
}
问题:
1.是否为每个查询打开一个新连接?如果是这样,那么不建议单独使用上述查询?
2. 另外,你能告诉我有什么情况我必须使用存储过程而不是 LINQ 吗?
最佳答案
Does it open a new connection for each query?
有点。
When a query method is called, the connection is opened, and it remains open until the ObjectResult has been completely consumed or disposed.
但是,.NET 将连接合并,因此相同的连接对象 将被重用(我假设必要时会重新打开)。
请注意,在您枚举查询之前,查询不会执行(使用 foreach
、ToList
、ToArray
, Single
, First
等)。在那之前它只是一个查询。这意味着您必须在释放上下文之前对查询做一些事情,否则您将得到一个异常。
Are there any situations where I must use Stored Procedure instead of LINQ?
如果您的查询太复杂而无法使用 Linq 构建,那么存储过程是一个合理的选择。
关于c# - .Net 如何使用上下文处理 LINQ-To-Entity 中的连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23765331/