两个服务都使用 IUnitDataProvider 的 AddChildrenUnit 方法。
TemplateService 必须将此方法传递给已打开的连接对象,因为 CreateTemplate 方法必须在 AddTemplate 和“创建根单元节点”的事务中运行。
UnitService 没有将连接对象传递给 AddChildrenUnit 方法,因此代码无法编译!!!
我现在的问题是:我不能更改 AddChildrenUnit 方法并删除 sqlconnection 参数,否则 CreateTemplate 方法中的 AddChildrenUnit 将不再编译。
那我现在能做什么?我唯一能想到的是 AddChildrenUnit 的一个重载版本,一次带有 SqlConnection 参数,一个方法不带此参数。
太麻烦了...
你知道更好的解决方案吗?
模板服务:
public void CreateTemplate(Template template)
{
using (var transaction = new TransactionScope())
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
_templateDataProvider.AddTemplate(template,connection);
Unit rootUnit = new Unit{ TemplateId = template.TemplateId, ParentId = null, Name = "Root" };
_unitDataProvider.AddChildrenUnit(rootUnit,connection);
transaction.Complete();
}
}
单位服务:
public void AddChildrenUnit(Unit unit)
{
lock (this)
{
IEnumerable<Unit> childrenUnits = _unitDataProvider.GetChildrenUnits(unit.UnitId); // Selected ParentId
int hierarchyIndexOfSelectedUnitId = childrenUnits.Select(u => u.HierarchyIndex).DefaultIfEmpty(0).Max(c => c);
int hierarchyIndexOfNewChild = hierarchyIndexOfSelectedUnitId + 1;
unit.HierarchyIndex = hierarchyIndexOfNewChild;
_unitDataProvider.AddChildrenUnit(unit);
}
}
单位数据提供者:
/// <summary>
/// INSERT new child at the end of the children which is the highest HierarchyIndex
/// </summary>
/// <param name="unit"></param>
public void AddChildrenUnit(Unit unit) // 10 ms
{
using (var trans = new TransactionScope())
using (var con = new SqlConnection(_connectionString))
using (var cmd = new SqlCommand("INSERT INTO UNIT (Name,TemplateId,ParentId,CreatedAt,HierarchyIndex) VALUES (@Name,@TemplateId,@ParentId,@CreatedAt,@HierarchyIndex);Select Scope_Identity();",con))
{
con.Open();
// INSERT new child at the end of the children which is the highest HierarchyIndex
cmd.Parameters.AddWithValue("HierarchyIndex", unit.HierarchyIndex);
cmd.Parameters.AddWithValue("TemplateId", unit.TemplateId);
cmd.Parameters.AddWithValue("Name", unit.Name);
cmd.Parameters.Add("CreatedAt", SqlDbType.DateTime2).Value = unit.CreatedAt;
unit.UnitId = Convert.ToInt32(cmd.ExecuteScalar());
trans.Complete();
}
}