实体框架中对象上下文的处理4
我有一个从我的数据库模型自动生成的实体类。该类继承了ObjectContext,而ObjectContext又继承了IDisposable。
我创建了一个存储库,其中包含各种方法,这些方法使用实体对象的单个实例与数据库进行交互。
自动生成的类
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;
}
从这里您可以看到我对数据库实例进行了多次引用。我的问题是,我是否最好在每个方法中实例化一个新的 DevEntity,从而能够实现 using 语句,从而确保正确的处理,或者我当前的实现可以吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我也会在 Repository 类上实现
IDisposable
,这样它就可以处置ObjectContext
。如果每次返回不同的 ObjectContext,则在这些对象之间执行查询时可能会遇到问题,因为这些对象附加到不同的 ObjectContext,这将导致异常。定义:
用法:
这样做时,您的存储库会在使用后处理
ObjectContext
。I would implement
IDisposable
on the Repository class as well, so it can dispose theObjectContext
. If you return a different ObjectContext each time, you can run into problems when doing queries between those objects, as those are attached to differentObjectContext
s, which will result in an exception.Definition:
Usage:
Doing this, your repository takes care of disposing the
ObjectContext
after you used it.