2009-11-10 45 views
1

我在構建標準對象時遇到了一些麻煩。通常情況下,我同樣建立我cruteria這樣:將「ands」和「ors」組合起來的標準表達式

ISession session = GetSession(); 
ICriteria criteria = session.CreateCriteria(typeof(MyObject)) 
       .Add(Expression.Gt("StartDate", DateTime.Now.ToUniversalTime())) 
       .Add(Expression.Eq("SubObject.SubObjectId", subObjectId)) 
       .AddOrder(new Order("StartDate", true)); 

我需要做的就是創建這樣的標準大致如下:

WHERE((a.EndDate IS NOT NULL和 一.EndDate> ='{Now}')OR a.EndDate is NULL)AND((a.SubObject IS NOT NULL AND a.SubObject.SubObjectId ='{Id}') OR a.SubObject IS NULL)AND開始日期< ='{Now}'

是的,我知道我可以使用HQL,但如果可能的話,我想使用Critera來代替。

子對象和enddate可以爲空,如果它們爲空我想將它們包含在選擇中,但如果它們不爲null,則需要將它們與值進行比較。子對象的id如果不爲null,則當前時間如果enddate不爲null。

我知道我需要對「OR」進行析取,但我不確定它們的位置和順序,只要符合標準。

回答

1
var now = DateTime.Now; 
var myObjects = session 
    .CreateCriteria<MyObject>() 
    .CreateAlias("SubObject", "so") 
    .Add(
     Expression.And(
      Expression.Or(
       Expression.And(
        Expression.IsNotNull("SubObject"), 
        Expression.IdEq(10) 
       ), 
       Expression.IsNull("SubObject") 
      ), 
      Expression.And(
       Expression.Or(
        Expression.And(
         Expression.IsNotNull("EndDate"), 
         Expression.Ge("EndDate", now) 
        ), 
        Expression.IsNull("EndDate") 
       ), 
       Expression.Le("StartDate", now) 
      ) 
     ) 
    ) 
    .List<MyObject>();