2012-09-13 33 views
0

在項目中,我試圖打造專業化的標準是這樣的:如何從兩個foreach構建NHibernate或標準?

ICriteria criteria = session.CreateCriteria(typeof(Orders), typeof(Orders).Name); 

if (param != null) 
{      
    if (param[1] != "System") 
    { 
     for (int index = 0; index < param.Length - 1; index++) 
     { 
      if (!string.IsNullOrEmpty(param[index])) 
      {         
       criteria.Add(Expression.Eq(
        "RealizationPoint", 
        CommonUtils.GetNameRealizationPointById(param[index]))); 
      } 
     } 
    } 
    if (param[1] != "System" && param2 != null && 
     !string.IsNullOrEmpty(param2[0])) 
    { 
     for (int index = 0; index < param2.Length - 1; index++) 
     { 
      if (!string.IsNullOrEmpty(param2[index])) 
      { 
       criteria.Add(Expression.Eq(
        "RealizationPoint", 
        CommonUtils.GetNameRealizationPointById(param2[index]))); 
      } 
     } 
    } 
} 

PARA1,參數2:字符串[]參數1,字符串[]參數2。 在表達逗留和結果之間,我需要OR。

回答

1

您可以使用Restrictions.Disjunction()將多個表達式分組爲OR,並將Restrictions.Conjuctions()分組爲AND。

簡單的例子:

var conjunction1 = Restrictions.Conjunction(); 
for (int index = 0; index < param.Length -1; index++) 
{ 
    conjunction1.Add(Restrictions.Eq("RealizationPoint", param[index])); 
} 

var conjunction2 = Restrictions.Conjunction(); 
for (int index = 0; index < param2.Length -1; index++) 
{ 
    conjunction2.Add(Restrictions.Eq("RealizationPoint", param2[index])); 
} 

criteria.Add(Restrictions.Disjunction().Add(conjunction1).Add(conjunction2)); 

// Or with Restrictions.Or() 
// criteria.Add(Restrictions.Or(conjunction1, conjunction2)); 

你可以在這太問題的詳細信息和替代:How to create OR statements for NHibernate?