简体   繁体   English

在实体框架中使用“使用”语句的正确方法

[英]Correct way of using the 'using' statement in Entity Framework

I have some questions about using the using statement. 我对使用using语句有一些疑问。 I understand what it does (If I'm correct, it disposes all open connections and such), but I'm unsure how I should use it correctly. 我知道它的作用(如果正确,它将处理所有打开的连接等),但是我不确定如何正确使用它。

The project I'm working in doesn't contain any repositories, which you don't need for Entity Framework. 我正在处理的项目不包含任何存储库,而Entity Framework则不需要。

So basically, I'm getting a list of Guids as parameter in my method. 所以基本上,我在我的方法中得到了Guid列表作为参数。 These ids are for restaurants, and I want to retrieve all reviews that have been given on these restaurants. 这些ID适用于餐厅,我想检索这些餐厅的所有评论。

So currently, I'm retrieving the list like so: 因此,目前,我正在像这样检索列表:

public void DoSomething(List<Guid> restaurantIds)
{
    List<Review> reviews;
    using (var db = new Context())
    {
        reviews = db.Reviews.Where(x => restaurantIds.Contains(x.RestaurantId)).ToList();
    }
    //More stuff here
}

Is this a common bad practice to declare the list outside of the using statement? 在using语句之外声明列表是否是常见的不良做法? I thought of a few alternatives, but I'm (again) unsure what would be better. 我想到了一些替代方案,但是(再次)我不确定会更好。

  1. Create a seperate method in the same class which does exactly that and returns the list. 在相同的类中创建一个单独的方法,即可完成该操作并返回列表。 This way in my DoSomething method, I can just use it like this: List<Review> reviews = GetReviewsFromRestaurants(restaurantIds); 这样,在我的DoSomething方法中,我可以像这样使用它: List<Review> reviews = GetReviewsFromRestaurants(restaurantIds);
  2. I have to create the context first, and then use the LINQ statement without the using block. 我必须先创建上下文,然后使用不带using块的LINQ语句。 I have to call .Dispose() when I'm done with it though. 完成后,我必须调用.Dispose()

Is there a problem when I use the using statement like in my example? 在我的示例中使用using语句时是否存在问题? If so, are the alternatives better? 如果是这样,替代方案是否更好? And if that's not the case, could you give me an example on how I should retrieve this list? 如果不是这种情况,您能举个例子说明如何检索此列表吗?

Here in this case braces defines their own scope. 在这种情况下,括号定义了它们自己的范围。 The variables which you will declare outside the scope of braces will be visible inside braces and its okay. 您将在大括号范围之外声明的变量将在大括号内部可见,并且可以。

Its actually the shorthand for try catch block. 它实际上是尝试捕获块的简写。

List<Review> reviews;
var db = new Context();
try
{
   reviews = db.Reviews.Where(x => restaurantIds.Contains(x.RestaurantId)).ToList();
}
finally
{
  db.Dispose();
} 

And your snippet is much more concise than this. 您的摘要比这要简洁得多。 Compiler will always call .Dispose on the "used" object. 编译器将始终在.Dispose对象上调用.Dispose

About the reviews variable, I do not think it is bad that you declare it outside of using block. 关于reviews变量,我认为在using块之外声明它并不坏。

1. Separate method is recommended. 1.建议使用单独的方法 Actually you can still use a repository class ( RestaurantRepository ) that will handle all these basic operations like: get all restaurants based on a single or multiple identifier, create a new restaurant, change some data for a restaurant. 实际上,您仍然可以使用存储库类( RestaurantRepository )来处理所有这些基本操作,例如:根据单个或多个标识符获取所有餐厅,创建新餐厅,更改餐厅的某些数据。

This ensures that you separate your business logic from basic operations. 这样可以确保您将业务逻辑与基本操作分开。

2. Disposable context vs. explicit Dispose() . 2.一次性上下文与显式Dispose()的比较 Disposable context is clearly better since it you make sure that Dispose() is called even if your code fails. 一次性上下文显然更好,因为即使您的代码失败,您也可以确保调用Dispose()。

Bigger picture - Entity framework and context dispose 更大的图景 -实体框架和上下文处理

This is already discussed here . 这已经在这里讨论 Also, this article shows that dispose is not so necessary as it seems. 此外, 本文还显示,处置似乎并没有必要。

Personally, I have been Unit of Work pattern to allow multiple changes (on various repositories / entities) and did not get into trouble for not disposing the context. 就我个人而言,我一直是“工作单位”模式,允许(在各种存储库/实体上)进行多种更改,并且不会因不处理上下文而遇到麻烦。

There usually is no one-size-fits-all answer to "what is a bad practice" and your question is no exception. 对于“什么是不好的做法”,通常没有一个万能的答案。您的问题也不例外。 While often thare are clearly bad prectices and sometimes clearly good practices, there is a lot of factors that influence your decision (such as your requirements, the rules of your organization or the experience of your team). 尽管包装纸通常是不好的选择 ,有时甚至是好的做法,但是有很多因素会影响您的决定(例如您的要求,组织的规则或团队的经验)。

You can keep a context in entity framework for longer than just a moment (although keeping it open for very long might also not be a good idea), as long as you are sure you dispose it at the end. 当你确定你的最终处置它你也可以在实体框架上下文的不仅仅是一时长(虽然保持其开放长时间也可能不是一个好主意),只要。 But there is also nothing wrong in that way you apply using to your context. 但也有什么错在您应用的方式using你的环境。 In web applications contexts are often used for a very short time and low-level connection pooling usally keeps the solution still performant. 在Web应用程序中,上下文通常用于很短的时间,并且低级连接池通常使解决方案保持高性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM