2014-07-18 64 views
1

我一直在網上研究它一段時間,但他們非真正使我感覺..也許我是新的Hibernate。Nhibernate如何進行內部連接和匹配模式?

但是客戶表想加入,然後customerProduct表連接產品表 和我有一個字符串變量的產品,我想能夠匹配在SQL Server的產品表名稱值列 .. 查詢我想做

select c.Name, c.Address1, c.Address2, c.County, p.Name 
from dbo.Customers as c inner join dbo.CustomerProducts as cp 
    on c.CustomerID = cp.CustomerID inner join dbo.Products as p 
    on cp.ProductID = p.ProductID 
where c.Address1 ='&somthing&' and c.Name='&somthing&' and c.Address1='&somthing&' and p.Name='&somthing&' 

然而,這是我的時刻,我想不出如何做一個內NHibernate的 加入,並把字符串變量產品搜索產品表

public IPagedList<Customer> GetSearchPagedCustomer(string product, string practice, string address, string county, int pageNumber = 1, int pageSize = 100) 
     { 
      ICriteria criteria = Session.CreateCriteria<Customer>(); 
      if (!string.IsNullOrEmpty(product)) 
       criteria.Add(Restrictions.Like("Product.Name",product,MatchMode.Anywhere)); 

      if (!string.IsNullOrEmpty(practice)) 
       criteria.Add(Restrictions.Like("Name", practice,MatchMode.Anywhere)); 

      //One value and search 3 column: address 1, address 2 and address 3 
      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>().OrderBy(x => x.Name).ToPagedList<Customer>(pageNumber, pageSize); 
    } 

任何人都可以將該SQL查詢代碼轉換爲Nhibernate代碼爲我,, 非常感謝您!

回答

1

我猜,你的映射會<bag><many-to-many>和客戶有一個集合產品:

public class Customer 
{ 
    public virtual IList<Product> Products { get; set; } 
    public virtual string Name { get; set; } 
    ... 

那麼怎樣的方式做一個加盟會是這樣的:

ICriteria criteria = Session.CreateCriteria<Customer>(); 

if (!string.IsNullOrEmpty(product)) 
{ 
    // here we do LEFT JOIN on Products 
    var productCriteria = criteria 
      .CreateCriteria("Products", "Product", JoinType.LeftOuterJoin); 

    // the subcriteria targeting the products table 
    productCriteria.Add(Restrictions.Like("Name",product,MatchMode.Anywhere)); 
} 
... 

而且此外,我們可以在服務器上進行分頁和排序

criteria 
    .SetMaxResults(pageSize) 
    .SetFirstResult(0) // calculate from pageNumber 
    .AddOrder(new Order("Name", true)) 
    .Future<Customer>() 
    //.OrderBy(x => x.Name) 
    //.ToPagedList<Customer>(pageNumber, pageSize) 
; 
相關問題