【问题标题】:Help with conditional projection queries帮助条件投影查询
【发布时间】:2011-06-14 18:24:56
【问题描述】:

我有一个要求,我需要显示员工列表及其角色。因此,如果员工的角色是会计,我想显示该员工的名字和姓氏。下面是我的代码

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

【问题讨论】:

    标签: c# nhibernate nhibernate-criteria nhibernate-projections


    【解决方案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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 2017-04-14
      相关资源
      最近更新 更多