1

我有一个要求,我需要显示一个员工及其角色列表。所以如果员工的角色是会计,我想显示该员工的名字和姓氏。以下是我的代码有条件投影查询帮助

SearchTemplate RoleTemplate = new SearchTemplate(); 
      RoleTemplate.Criteria = DetachedCriteria.For(typeof(CompanyRole), "CR"); 

     RoleTemplate.Criteria.CreateCriteria("User", "User") 
     .SetProjection(Projections.ProjectionList() 
      .Add((Projections.Conditional 
         (Restrictions.Eq("CR.Role", Role.Accounting), 
           Projections.Property("User.FirstName"), Projections.Property("User.FirstName"))), "Account") 
           .Add((Projections.Conditional 
         (Restrictions.Eq("CR.Role", Role.Manager), 
           Projections.Property("User.FirstName"), Projections.Property("User.FirstName"))), "Manager")); 

公司角色表具有userid作为用户表的主键ID的外键。如何在上面的“帐户”和“经理”字符串中获取名字姓氏字段。上面的代码不起作用,它会在字符串中放入冗余的名称值。另外,我有一个LastName字段,我想将它附加到两个字符串中的FirstName。任何人都可以请解释我将如何实现这一目标?另外,在上面的查询中我使用了两次projection.property,我知道这是错误的,但我只是想知道我在找什么。

回答

1

它必须在sql语句中吗?难道它不够:

var result = CreateCriteria<User>() 
    .CreateAlias("CompanyRole", "cr") 
    .SetProjection(Projections.ProjectionList() 
     .Add(Projections.Property("FirstName")) 
     .Add(Projections.Property("LastName")) 
     .Add(Projections.Property("cr.Role")) 
     ) 
    .List<object[]>(); 

foreach (var item in result) 
{ 
    string name = string.Concat(item[0], item[1]); 
    Role role = (Role)item[2]; 

    // do something with name and role 
}