I have some questions about using the using
statement. 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.
So basically, I'm getting a list of Guids as parameter in my method. These ids are for restaurants, and I want to retrieve all reviews that have been given on these restaurants.
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? I thought of a few alternatives, but I'm (again) unsure what would be better.
- 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);
- I have to create the context first, and then use the LINQ statement without the using block. I have to call
.Dispose()
when I'm done with it though.
Is there a problem when I use the using
statement like in my example? 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?