我的方法是否正确将服务层中的TransactionScope中的所有3个dataprovider.GetXXX方法捆绑为UnitOfWork?
你会做些不同的事吗?
TransactionScpe ts从哪里知道具体的ConnectionString?
我应该从我的连接获取Transaction对象并将此Transaction objekt传递给TransactionScope的构造函数吗?
像AdministrationService.cs一样的服务层
private List<Schoolclass> GetAdministrationData()
{
List<Schoolclass> schoolclasses = null
using (TransactionScope ts = new TransactionScope())
{
schoolclasses = _adminDataProvider.GetSchoolclasses();
foreach (var s in schoolclasses)
{
List<Pupil> pupils = _adminDataProvider.GetPupils(s.Id);
s.Pupils = pupils;
foreach (var p in pupils)
{
List<Document> documents = _documentDataProvider.GetDocuments(p.Id);
p.Documents = documents;
}
}
ts.Complete();
}
return schoolclasses;
}
示例DataProvider中的这3个方法中的任何一个如何:
public List<Schoolclass> GetSchoolclassList()
{
// used that formerly without TransactionSCOPE => using (var trans = DataAccess.ConnectionManager.BeginTransaction())
using (var com = new SQLiteCommand(DataAccess.ConnectionManager))
{
com.CommandText = "SELECT * FROM SCHOOLCLASS";
var schoolclasses = new List<Schoolclass>();
using (var reader = com.ExecuteReader())
{
Schoolclass schoolclass = null;
while (reader.Read())
{
schoolclass = new Schoolclass();
schoolclass.SchoolclassId = Convert.ToInt32(reader["schoolclassId"]);
schoolclass.SchoolclassCode = reader["schoolclasscode"].ToString();
schoolclasses.Add(schoolclass);
}
}
// Used that formerly without TransactionSCOPE => trans.Commit();
return schoolclasses;
}
}
答案 0 :(得分:1)
这看起来很好 - 这就是TransactionScope
的用途,在代码中提供事务控制(这是UoW的常见模式)。
TransactionScpe ts从哪里知道具体的ConnectionString?
没有。这取决于您的数据访问层,对TransactionScope
并没有多大意义。 TransactionScope
所做的是创建一个事务(默认情况下是一个轻量级事务) - 如果您的数据访问跨越多个数据库,事务将自动升级到分布式事务。它使用MSDTC。
我应该从我的连接获取Transaction对象并将此Transaction objekt传递给TransactionScope的构造函数吗?
不,不,不。见上文。做你现在正在做的事。嵌套TransactionScope
s。