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 的外键。如何在上面的“Account”和“Manager”字符串中获取 Firstname Lastname 字段。上面的代码不起作用,它将名称的冗余值放在两个字符串中。另外,我有一个姓氏字段,我想将其附加到两个字符串中的名字。谁能解释我将如何实现这一目标?此外,在上面的查询中,我使用了两次 projections.property,我知道这是错误的,但我只是想知道我在寻找什么。

4

1 回答 1

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
}
于 2011-06-20T16:19:38.213 回答