2016-02-22 80 views
1

我目前正在努力研究如何用實體框架和Linq替換我們所有的跨數據庫連接,我已經設法讓我的代碼的一部分工作,但真正讓它有點惱人的是冗長和聯接的複雜性。有沒有簡化代碼的方法,或者我堅持使用冗長冗長的亂碼?減少Linq加入的冗長?

一個例子:

using (var context = new CustomerContext(CustomerID)) 
using (var e = new eContext()) 
{ 
    var globalUserList = e.GlobalLoginCustomerBridges 
     .Join(e.GlobalLogins, 
      glcb => glcb.glcbr_gl_id, 
      gl => gl.gl_id, 
      (glcb, gl) => new { glcb, gl }) 
     .Where(n => n.glcb.glcbr_customer_id == CustomerID) 
     .Select(n => new User2 
     { 
      ID = (int)n.glcb.glcbr_user_id, 
      GlobalLogin = n.gl.gl_login_name, 
      GUID = n.gl.gl_GUID 
     }).ToList(); 

    var customer = e.Customers 
     .Join(e.DatabaseConnectionStrings, 
     c => c.DatabaseConnectionID, 
     d => d.DatabaseConnectionID, 
     (c, d) => new { c, d }) 
     .Select(n => new Customer2 
     { 
      ID = n.c.CustomerID, 
      Name = n.c.CustomerName, 
      DatabaseConnectionName = n.d.DatabaseConnectionName, 
      DatabaseConnectionString = n.d.DatabaseConnectionString1, 
      GUID = n.c.cust_guid, 
     }).ToList().FirstOrDefault(n => n.ID == CustomerID); 

    var orgs = context.Organizations 
     .Select(o => new Organization2 
     { 
      ID = o.org_id, 
      Name = o.org_name, 
     }).ToList(); 

    var users = context.Users 
     .Select(n => new User2 
     { 
      ID = n.UserID, 
      FirstName = n.UserFirstName, 
     }).ToList(); 

    var userList = users 
     .Join(globalUserList, 
      u => u.ID, 
      gl => gl.ID, 
      (u, gl) => new { u, gl }) 
     .Join(context.OrganizationObjectBridges, 
      u => u.u.ID, 
      oob => oob.oob_object_id, 
      (u, oob) => new { u, oob }) 
      .Where(o => o.oob.oob_object_type_id == 9) 
     .Select(n => new User2 
     { 
      ID = n.u.u.ID, 
      GlobalLogin = n.u.gl.GlobalLogin, 
      FirstName = n.u.u.FirstName, 
      GUID = n.u.gl.GUID, 
      Customer = customer, 
      Organization = orgs.FirstOrDefault(o => o.ID == n.oob.oob_org_id) 
     }).Where(n => !isDisabled != null && n.Disabled == isDisabled).ToList(); 

    return userList; 
} 

在上面的代碼片段,我已經刪除〜代碼爲大部分的80%,簡直是字段映射,但它比錢包顯示的相當長的時間。

+0

正如法比奧在他的回答中所說的,儘可能地使用導航屬性而不是連接。如果您使用LINQ-to-SQL開始思考對象的層次結構而不是表格數據結構。 –

回答

2

看起來前2個查詢不需要連接,因爲它們屬於同一個數據庫。你不能使用導航屬性嗎?請記住只在不具有物理(導航屬性)關係的對象之間使用連接。

關於最後一個查詢,您可以使用linq查詢而不是鏈式方法(這使得代碼更具可讀性,在我看來)。這將是這樣的:

var userList = from user in users 
       join gul in globalUserList on user.ID = gul.ID 
       join oob in context.OrganizationObjectBridges on user.ID = oob.oob_object.id 
       where oob.oob_object_type_id == 9 
       select new User2 
       { 
        ID = user.ID, 
        GlobalLogin = gul.GlobalLogin, 
        FirstName = user.FirstName, 
        GUID = gul.GUID, 
        Customer = customer, 
        Organization = orgs.FirstOrDefault(o => o.ID == n.oob.oob_org_id) 
       }; 

未經測試的代碼,我敢肯定它不會工作。我只是給你一些想法。

+1

Upvote用於建議使用導航屬性。對於從SQL遷移到LINQ的人來說,這似乎是一個常見問題。 –

+0

感謝提醒,我完全忘記了導航屬性。 –