问题
I have an entity class which is auto generated from my database model. This class inherits the ObjectContext which inturn inherits IDisposable.
I have created a repository that has various methods which use a single instance of the entity object to interact with the database.
Auto generated class
public partial class DevEntities : ObjectContext
{
public const string ConnectionString = "name=DevEntities";
public const string ContainerName = "DevEntities";
Repository Class
DevEntities db = new DevEntities();
public Customer GetCustomerByID(int id)
{
var customers = db.Customers.FirstOrDefault(c => c.CustomerId == id);
return customers;
}
public Customer GetCustomerByPasswordUsername(string email, string password)
{
var customers = db.Customers.FirstOrDefault(c => c.Email == email && c.Password == password);
return customers;
}
From this you can see that I make multiple references to the db instance. My question is, am I better to instantiate a new DevEntity within each method, thus being able to implement the using statement, and so ensure correct disposal, or is my current implementation ok?
回答1:
I would implement IDisposable on the Repository class as well, so it can dispose the ObjectContext. If you return a different ObjectContext each time, you can run into problems when doing queries between those objects, as those are attached to different ObjectContexts, which will result in an exception.
Definition:
public class Repository : IDisposable
{
DevEntities db = new DevEntities();
public Customer GetCustomerByID(int id)
{
var customers = db.Customers.FirstOrDefault(c => c.CustomerId == id);
return customers;
}
public Customer GetCustomerByPasswordUsername(string email, string password)
{
var customers = db.Customers.FirstOrDefault(c => c.Email == email && c.Password == password);
return customers;
}
public void Dispose()
{
db.Dispose();
}
}
Usage:
using(Repository r = new Repository())
{
//do stuff with your repository
}
Doing this, your repository takes care of disposing the ObjectContext after you used it.
来源:https://stackoverflow.com/questions/4579056/disposing-of-object-context-in-entity-framework-4