我有一个从我的数据库模型自动生成的实体类.该类继承了内部继承IDisposable的ObjectContext.
我创建了一个存储库,它具有使用实体对象的单个实例与数据库交互的各种方法.
public partial class DevEntities : ObjectContext { public const string ConnectionString = "name=DevEntities"; public const string ContainerName = "DevEntities";
存储库类
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; }
从这可以看到我对数据库实例进行多次引用.我的问题是,我最好在每种方法中实例化一个新的DevEntity,从而能够实现使用语句,因此确保正确的处理,还是我目前的实现?
解决方法
我也将在Repository类上实现IDisposable,因此它可以处理ObjectContext.如果每次返回不同的ObjectContext,那么在这些对象之间进行查询时可能会遇到问题,因为这些对象连接到不同的ObjectContext,这将导致异常.
定义:
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(); } }
用法:
using(Repository r = new Repository()) { //do stuff with your repository }
这样做,您的存储库在使用它后处理ObjectContext.