0

我做我的unitservice被调用UnitDataProvider类2种方法这个伪代码。业务服务调用数据访问层的多种方法每打开一个连接

var units = dataProvider.GetChildrenUnits(parentId); 
unit.HierarchyIndex = units.Where(u => u.TemplateId == unit.TemplateId && u.ParentId == null).Max(u => u.HierarchyIndex) + 1; 
dataProvider.AddSiblingUnit(unit); 

每种方法都会打开一个连接。

这怎么可能被refactorized只使用1个连接或重用打开的连接?

或者你认为正常为每个数据提供程序方法调用的连接?

SOLUTION:数据库中的所有数据访问逻辑是DAL不是BLL内,我认为下面的是我的企业它只是数据库逻辑没有业务逻辑进行。

public void AddSiblingUnit(Unit unit) 
     { 
      if (unit.ParentId == null) 
      { 
       throw new OnlyOneRootNodeIsAllowedException("Only one Root node is allowed!", null); 
      } // Server side check if the root is selected because 2 root units are not allowed 

      lock (_lockObject) 
      { 
       using (var trans = new TransactionScope()) 
       using (var con = new SqlConnection(_connectionString)) 
       using (var cmd = new SqlCommand()) 
       { 
        cmd.Connection = con; 
        con.Open(); 

        // SELECT HierarchyIndex for the new inserted sibling 
        string selectCommandText = "SELECT HierarchyIndex FROM UNIT WHERE UnitId = @UnitId"; // UnitId of the selected sibling 
        cmd.CommandText = selectCommandText; 
        cmd.Parameters.AddWithValue("UnitId", unit.UnitId); // the parentId which is the selected UnitId 
        int hierarchyIndexOfSelectedSibling = Convert.ToInt32(cmd.ExecuteScalar()); 
        int hierarchyIndexOfNewSibling = hierarchyIndexOfSelectedSibling + 1; 

        // UPDATE all sibling units whose HierarchyIndex is greater than the HierarchyIndex of the selected sibling 
        string updateCommandText = "UPDATE UNIT SET HierarchyIndex = HierarchyIndex + 1 WHERE HierarchyIndex >= @HierarchyIndex AND ParentId = @ParentId"; 
        cmd.CommandText = updateCommandText; 
        cmd.Parameters.AddWithValue("HierarchyIndex", hierarchyIndexOfNewSibling); 
        cmd.Parameters.AddWithValue("ParentId", unit.ParentId); 
        cmd.ExecuteNonQuery(); 

        // INSERT new sibling 
        string insertCommandText = "INSERT INTO UNIT (Name,TemplateId,CreatedAt,HierarchyIndex,ParentId) VALUES (@Name,@TemplateId,@CreatedAt,@HierarchyIndex,@ParentId);Select Scope_Identity();"; 
        cmd.CommandText = insertCommandText; 
        cmd.Parameters.AddWithValue("Name", unit.Name); 
        cmd.Parameters.AddWithValue("TemplateId", unit.TemplateId); 
        cmd.Parameters.Add("CreatedAt", SqlDbType.DateTime2).Value = unit.CreatedAt; 
        unit.UnitId = Convert.ToInt32(cmd.ExecuteScalar()); 

        trans.Complete(); 
       } 
      } 
     } 

回答

0

您可以在dataProvider类中使用连接池。

这将允许您重新使用连接,但如果您打算让您的应用程序成为多线程,那么与此方法有问题。除非你确定你的连接池有一个线程安全的实现,这说起来容易做起来难。

+0

确定上述方法是不完整的。现在该方法有3个数据提供者调用。一个GetXX,一个UpdateSiblings和AddSibling。在跨越所有3个数据提供者方法的UnitService中使用TransactionScope有什么用?然后每个数据提供者方法也必须传递一个连接对象。你怎么看? – Elisabeth

+0

啊是的...应用程序将是多线程的。 – Elisabeth

+0

这可以工作,但我很好奇你将如何抽象,以便从外部看不到它。此外,应用程序是基于Web还是桌面? – linkerro

相关问题