如何仅对查询添加非空/空限制

时间:2012-02-12 18:11:09

标签: nhibernate

您是否知道如何编写以下代码更好/更短:) 我需要检查字段表单是否为空,然后添加 查询的标准, 谢谢:)

AbstractCriterion restrictions = null; 

if (model.DateFrom != null) 
  AddRestriction(ref restrictions, 
   Restrictions.Ge(Projections.Property<Invoice>(x => x.DateIn), model.DateForm)); 

if (model.DateTo != null) 
  AddRestriction(ref restrictions, 
    Restrictions.Le(Projections.Property<Invoice>(x => x.DateIn), model.DateTo)); 

if (!string.IsNullOrEmpty(model.Prop1)) 
   AddRestriction(ref restrictions, 
     Restrictions.Eq(Projections.Property<Invoice>(x => x.Prop1), model.Prop1)); 

// ... many more conditions :) 

return m_session.QueryOver<Invoice>().Where(restrictions).List();

1 个答案:

答案 0 :(得分:1)

初学者不需要ref关键字。我认为这更好,而不会牺牲可读性:

var query = session.QueryOver<Invoice>();

Action<object, ICriterion> addIfNonNull = (o, c) =>
                                            {
                                                if (o != null)
                                                {
                                                    query.And(c);
                                                }
                                            };

addIfNonNull(model.Prop1, Restrictions.Eq(Projections.Property<Invoice>(x => x.Prop1), model.Prop1));