0

给定数据访问对象和具有从循环调用的Data签名的此数据访问对象的方法,重用 EF 数据上下文而不是为循环中的每个调用创建它的最佳方法是什么?public void GetEntityAttributesValues(int sessId, int entId)foreach

环形:

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();
            }
        }
    }

因此,每次从循环中调用此方法时,我不想在 using 块中创建新上下文,而是重用数据上下文......

4

1 回答 1

0

我认为使用数据上下文的最佳方法是同时使用 IoC 和存储库模式,在设置 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);
    }

}

于 2012-07-05T23:35:58.550 回答