给定数据访问对象Data
以及从public void GetEntityAttributesValues(int sessId, int entId)
循环调用签名foreach
的此数据访问对象的方法,重用EF数据上下文的最佳方法是什么为循环中的每个调用创建它?
循环:
foreach (var ord in Data.Entities.Where(m => m.SessionId == CurrentSessionId))
{
Data.GetEntityAttributesValues(sid, ord.Id);
...
}
方法:
public void GetEntityAttributesValues(int sessId, int entId)
{
var tsOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted };
using (var scope = new TransactionScope(TransactionScopeOption.Required, tsOptions))
{
using (var context = new MyDataEntities(MyDataConnection))
{
var attVals = context.OrderAttributeValues.Where(a => a.SessionId == sessId
&& a.OrderId == entId).ToList();
foreach (var attVal in attVals)
{
var att = Attributes.Single(a => a.Key == attVal.AttributeId);
AttributeValues[att.Value] = attVal.AttributeValue;
}
scope.Complete();
}
}
}
因此,每次从循环调用此方法时,我都不会在使用块中创建新的上下文,而是希望重用数据上下文...
答案 0 :(得分:0)
我认为使用数据上下文的最佳方法是一起使用IoC和Repository模式,在设置类似IoC的结构图(https://github.com/webadvanced/Structuremap-MVC3)之后,您可以使用存储库这样:
public class DatabaseFactory : Disposable, IDatabaseFactory
{
private DatabaseContext _database;
public DatabaseContext Get() {
return _database ?? (_database = new DatabaseContext());
}
protected override void DisposeCore() {
if (_database != null)
_database.Dispose();
}
}
和
public class FooRepository : IFooRepository {
private readonly DatabaseContext _database;
private readonly IDatabaseFactory _databaseFactory;
private readonly IDbSet<Foo> _dbset;
public MyRepository (IDatabaseFactory databaseFactory) {
_databaseFactory = databaseFactory;
_database = _database ?? (_database = _databaseFactory.Get());
_dbset = _database.Set<Foo>();
}
protected DatabaseContext Database {
get { return _database; }
}
public virtual void Add(Foo entity) {
_dbset.Add(entity);
}
}