2016-09-08 49 views
1

另一個名單上有以下是他們的對象的選擇列表包含通過LINQ

enter image description here

我已經以下是他們的

class RoleDTO 
{ 
    string RoleId; 
    string EnglishName; 
    Guid TypeId; 
    List<ClaimDTO> claims; 
} 

class ClaimDTO 
{ 
    string ActionID; 
    string ActionCode; 
    string ActionLevel; 
    string GrantDate; 
} 

現在我想要兩個DTO類三個數據庫模型從數據庫中檢索對象列表RoleDTO。到目前爲止,我試過

public List<RoleDTO> GetRoleByType(Guid roleTypeId) 
{ 
    var roleDTOs = (from r in ctx.Roles 
      join rc in ctx.RoleClaims on r.RoleID equals rc.RoleID 
      join a in ctx.Actions on rc.ActionID equals a.ActionID 
      where r.RoleTypeID == roleTypeId 
      select new RoleDTO 
      { 
       RoleId = r.RoleID, 
       EnglishName = r.EnglishName, 
       TypeId = r.TypeID, 
       claims = List of ClaimDTO objects related to this role 
      }).ToList(); 

    return roleDTOs; 
} 

我的問題是我怎麼能檢索SELECT語句中ClaimDTO對象列表。我的linq是否正確? 我使用Telerik OpenAccess作爲ORM

+0

索賠= r.claims。選擇(x =>在此輸入更多代碼) – jdweng

回答

0

下面的變化應該有助於得到的結果

public List<RoleDTO> GetRoleByType(Guid roleTypeId) 
{ 
    var roleDTOs = (from r in ctx.Roles 
    join rc in ctx.RoleClaims on r.RoleID equals rc.RoleID 
    where r.RoleTypeID == roleTypeId 
    select new RoleDTO 
    { 
     RoleId = r.RoleID, 
     EnglishName = r.EnglishName, 
     TypeId = r.TypeID, 
     claims = ctx.Actions.Where(c => c.ActionId == rc.ActionId).Select(s => new ClaimDTO 
     { 
     ActionID = s.ActionID, 
     ActionCode = s.ActionCode, 
     ActionLevel = s.ActionLevel, 
     GrantDate = s.GrantDate 

     })ToList() 


    }).ToList(); 

return roleDTOs; 
} 

另一種選擇

List<ClaimDTO> claimsList = ctx.Actions.Select(s => new ClaimDTO 
     { 
     ActionID = s.ActionID, 
     ActionCode = s.ActionCode, 
     ActionLevel = s.ActionLevel, 
     GrantDate = s.GrantDate 

     })ToList(); 

var roleDTOs = ctx.Roles.Join(ctx.RoleClaims, r => r.RoleID, rc => rc.RoleID, (r,rc) => new 
      { 
      r,rc 
      }).Where(r => r.RoleTypeID == roleTypeId) 
      .Select(row => new RoleDTO 
      { 
       RoleID = row.r.RoleID, 
       EnglishName = row.r.EnglishName, 
       TypeID = row.r.TypeID, 
       claims = claimsList.Where(c => c.ActionId == rc.ActionId) 
      }).ToList(); 

如果你使用的方法包括以下然後查詢可以幫助

var roleDTOs = ctx.Roles.Include("RoleClaims").Join(ctx.Actions, r => r.RoleClaims.Select(rc => rc.ActionID).FirstOrDefault() , a => a.actionid , (r,a) => new 
      { 
       r,a 
      }.Where(r => r.RoleTypeID == roleTypeId) 
      .Select(row => new RoleDTO 
      { 
       RoleID = row.r.RoleID, 
       EnglishName = row.r.EnglishName, 
       TypeId = row.r.RoleTypeID, 
       Claims = row.a.Select(c => new ClaimDTO 
       { 
        ActionID = c.ActionID, 
        ActionCode = c.ActionCode, 
        ActionLevel = c.ActionLabel, 
        GrantDate = row.r.RoleClaims.Select(g => g.grantDate) 

       }) 

      }).ToList(); 
+0

索賠是對象清單。 –

+0

現在編輯從列表中檢索 –

+0

這將在轉換LINQ到SQL期間返回exeption –

相關問題