【问题标题】:Need help optimizing a NHibernate criteria query that uses Restrictions.In(..)需要帮助优化使用 Restrictions.In(..) 的 NHibernate 条件查询
【发布时间】:2010-05-07 21:22:27
【问题描述】:

我试图弄清楚是否有一种方法可以通过子查询或其他更优化的方式严格使用 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>();
}

【问题讨论】:

  • 经理和客户之间的映射是什么?
  • @dotjoe 员工(后备经理)* -> * 客户。员工(主要经理)1 -> * 客户。因此,您有 IList manager.ManagedCustomers 和 IList manager.BackedCustomers。您还有 Employee customer.PrimaryManager 和 IList customer.BackupManagers.
  • 哦,那么您应该加入 BackupManagers。我将发布一个示例。

标签: nhibernate criteria detachedcriteria


【解决方案1】:
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>();

我在那里扔了一个不同的,因为我不确定是否有可能让备份和主要是同一个人。

【讨论】:

  • 像魅力一样工作。我不知道别名具有与之关联的 SQL 连接类型的能力。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-05
  • 2012-10-14
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多