给定数据访问对象和具有从循环调用的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 块中创建新上下文,而是重用数据上下文......