I'm starting with the Entity Framework and the repository pattern. I'm confused about the ObjectContext. Is it better to instantiate it each time we need it? I'm using like that:
private GenericRepository _genericRepository;
public EmployeeDAO()
{
var _context = new NorthwindEntities();
this._genericRepository = 开发者_开发知识库new GenericRepository(_context);
}
public Employee FindByID(int employeeID)
{
Employee _employee = this._genericRepository.Single<Employee>(x => x.EmployeeID == employeeID );
return _employee;
}
Not sure what exactly you mean by Global
, but a singleton ObjectContext
is not a good idea. The ObjectContext
is a Unit of work, and should be pretty much short lived. The exact implementation details may depend on what kind of application you are developing. E.g. for a web application it is quite common to have one ObjectContext
instance per web request.
You can also check out similar questions here:
Entity Framework 4 ObjectContext Lifetime
EF - and repository pattern - multiple contexts
精彩评论