Sql 具有不同属性的Nhibernate查询

Sql 具有不同属性的Nhibernate查询,sql,nhibernate,Sql,Nhibernate,我遇到一个查询问题,该查询在一个表中返回2条相同的客户记录,, 所以在我的数据库中,我得到了一个客户表,一个客户产品表和一个产品表, 客户可以有很多产品 public IPagedList<Customer> SearchCustomer(string product, string address, string county) { ICriteria criteria = Session.CreateCriteria<Customer

我遇到一个查询问题,该查询在一个表中返回2条相同的客户记录,, 所以在我的数据库中,我得到了一个客户表,一个客户产品表和一个产品表, 客户可以有很多产品

public IPagedList<Customer> SearchCustomer(string product, string address, string county)
        {
            ICriteria criteria = Session.CreateCriteria<Customer>()

            .CreateAlias("CustomerProducts", "cp")
            .CreateAlias("cp.Product", "p");

            if (!string.IsNullOrEmpty(product))
            {
                criteria.Add(Restrictions.Like("p.Name", product));
            }
            if (!string.IsNullOrEmpty(address))
            {
                criteria.Add(Restrictions.Like("Address1", address, MatchMode.Anywhere));
            }
            if (!string.IsNullOrEmpty(county))
            {
                criteria.Add(Restrictions.Like("County", county, MatchMode.Anywhere));
            }

            return criteria.Future<Customer>();
}
公共IPagedList SearchCustomer(字符串产品、字符串地址、字符串县)
{
ICriteria条件=Session.CreateCriteria()
.CreateAlias(“客户产品”、“cp”)
.CreateAlias(“cp.Product”、“p”);
如果(!string.IsNullOrEmpty(产品))
{
标准。添加(限制,如(“p.Name”,产品));
}
如果(!string.IsNullOrEmpty(地址))
{
添加(限制,如(“Address1”,address,MatchMode.Anywhere));
}
如果(!string.IsNullOrEmpty(county))
{
添加(限制,如(“县”,县,匹配模式,任何地方));
}
返回条件。Future();
}
以上查询返回客户记录两次,因为客户有很多记录!! 任何关于如何解决此问题的想法/想法,都将非常有用

谢谢

实际上有两种方法:

1) 使用事后
Distinct
结果转换器:

criteria.SetResultTransformer(NHibernate.Transform.Transformers.DistinctRootEntity);
但我强烈建议:不要走这条路。您将永远无法应用分页

2) 不要加入集合,对(所有)集合使用批加载

因此,与其加入集合并创建cartesion产品,不如使用批量加载:

小城市:

NHibernate可以有效地利用批取,也就是说,如果访问一个代理(或集合),NHibernate可以加载多个未初始化的代理。批取是对惰性选择获取策略的优化。有两种方法可以调整批取:在类和集合级别

类/实体的批处理抓取更容易理解。假设您在运行时遇到以下情况:ISession中加载了25个Cat实例,每个Cat都有一个对其所有者Person的引用。Person类映射了一个代理,lazy=“true”。如果您现在遍历所有cat并对每个cat调用cat.Owner,则默认情况下,NHibernate将执行25条SELECT语句以检索代理的所有者。您可以通过在Person:

。。。
或对于集合:

<class name="Person">
    <set name="Cats" batch-size="3">
        ...
    </set>
</class>

...
有关更多详细信息,请务必遵守以下规定:


hmmm我是nhiberate的新手,您能告诉我怎么做吗?这并不复杂。正如代码片段所示。只需使用
batch size=“25”标记您的收藏即可
。就是这样。从那一刻起,不要在此集合中使用CreateAlias。只需查询根实体。一旦收到根实体列表,您就可以访问它们的集合,并且这些集合将以非常少的批次加载…尝试阅读有关批次大小的信息…非常酷的功能。我1)在任何地方都使用批次大小。。。2) 从不查询根目录及其集合。。然后,NHiberante可以非常快速有效地工作(无1+N选择),,是否将此XML标记添加到Nhibernate.config?你有什么好的例子/链接吗?谢谢你在用fluent吗?使用此选项:是否通过
.hbm.xml
文件使用映射?使用此选项:-我们正在讨论映射,因此此设置在您的案例中与集合
CustomerProducts
很高兴看到这一点,先生!;)享受NHibernate。。。神奇的工具;)
<class name="Person">
    <set name="Cats" batch-size="3">
        ...
    </set>
</class>