带标准的nhibernate子查询

时间:2014-08-20 16:10:44

标签: mysql sql nhibernate

我如何加入/添加SubQuery到标准?我想做的是能够创建一个SubQuery来搜索String Product,它是getCustomerProduct(两个表连接)。我也希望它能够进行soundex搜索。 我的问题是,我不确定我的子查询是否正确,除非我运行它,我如何将其添加到标准?我是新手,请求帮助!

   public IPagedList<Customer> GetSearchPagedCustomer(string product, string address, string county, int pagenumber, int pageSize)
     {
    ICriteria criteria = Session.CreateCriteria<Customer>();

                //.CreateAlias("Products", "cp")
                //.CreateAlias("cp.Product", "p");

                if (!string.IsNullOrEmpty(product))
                {
                    var getCustomerProduct = DetachedCriteria.For<Product>()
                        .SetProjection(Projections.Distinct(Projections.Property("Products.id")))
                        .CreateCriteria("Product", JoinType.InnerJoin)
                        .Add(Restrictions.Eq("Product.Name",product));

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

return criteria.Future<Customer>().ToPagedList<Customer>(pageNumber, pageSize);
}

1 个答案:

答案 0 :(得分:2)

sub-query应如下所示:

DetachedCriteria userSubquery = DetachedCriteria.For<Product>("product")
     // here we need to join the Many-to-many table - to later project customer
     .CreateCriteria("CustomerProducts", "cp", JoinType.InnerJoin)
     // Filter the Subquery
     .Add(Restrictions.Eq("product.Name", product)) // alias must fit 
     // SELECT The Customer Id  - projection from the join
     .SetProjection(Projections.Property("cp.CustomerId"));

     // root Customer criteria, filtered by the subquery
     criteria
       .Add( Subqueries.PropertyIn("ID", userSubquery) );

请把它作为草稿,因为我不知道确切的映射...

也许还要检查: