代码之家  ›  专栏  ›  技术社区  ›  Chris F

需要帮助优化使用Restrictions.In(..)的NHibernate条件查询吗

  •  1
  • Chris F  · 技术社区  · 16 年前

    我试图找出是否有一种方法可以严格使用Criteria和DetachedCriteria,通过子查询或其他更优化的方法来执行以下操作。NameGuidDto只不过是一个具有字符串和Guid属性的轻量级对象。

    public IList<NameGuidDto> GetByManager(Employee manager)
    {
        // First, grab all of the Customers where the employee is a backup manager.
        // Access customers that are primarily managed via manager.ManagedCustomers.
        // I need this list to pass to Restrictions.In(..) below, but can I do it better?
        Guid[] customerIds = new Guid[manager.BackedCustomers.Count];
    
        int count = 0;
        foreach (Customer customer in manager.BackedCustomers)
        {
            customerIds[count++] = customer.Id;
        }
    
        ICriteria criteria = Session.CreateCriteria(typeof(Customer))
                                    .Add(Restrictions.Disjunction()
                                                     .Add(Restrictions.Eq("Manager", manager))
                                                     .Add(Restrictions.In("Id", customerIds)))
                                    .SetProjection(Projections.ProjectionList()
                                                              .Add(Projections.Property("Name"), "Name")
                                                              .Add(Projections.Property("Id"), "Guid"))
    
        // Transform results to NameGuidDto
        criteria.SetResultTransformer(Transformers.AliasToBean(typeof(NameGuidDto)));
    
        return criteria.List<NameGuidDto>();
    }
    
    1 回复  |  直到 16 年前
        1
  •  1
  •   dotjoe    16 年前
    return Session.CreateCriteria<Customer>()
        .CreateAlias("BackupManagers", "bm", LeftOuterJoin)
        .Add(Restrictions.Disjunction()
            .Add(Restrictions.Eq("Manager", manager))
            .Add(Restrictions.Eq("bm.Id", manager.Id)))
        .SetProjection(Projections.Distinct(Projections.ProjectionList()
            .Add(Projections.Property("Name"), "Name")
            .Add(Projections.Property("Id"), "Guid")))
        .SetResultTransformer(Transformers.AliasToBean(typeof(NameGuidDto)))
        .List<NameGuidDto>();