這兩個服務都使用IUnitDataProvider的AddChildrenUnit方法。如何使用sql連接對象重載此數據訪問層方法
TemplateService必須將此方法傳遞給已打開的連接對象,因爲CreateTemplate方法必須在AddTemplate和「創建根單元節點」的事務中運行。
UnitService不會將連接對象傳遞給AddChildrenUnit方法,因此代碼不會編譯!
我現在的問題是:我無法更改AddChildrenUnit方法並刪除sqlconnection參數,否則CreateTemplate方法中的AddChildrenUnit將不再編譯。
那麼我現在可以做什麼?我能想到的唯一的事情是一次帶有SqlConnection參數的AddChildrenUnit的重載版本,以及一個沒有此參數的方法。
那很麻煩...
你知道更好的解決方案嗎?
TemplateService:
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();
}
}
UnitService:
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);
}
}
UNITDATAPROVIDER:
/// <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();
}
}