0

Do you have an idea how to write the following code nicer/shorter :) I need to check if the field form form is not empty and then add criterion to the query, thanks :)

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 Answer 1

1

You don't need the ref keyword for starters. I think this is nicer without sacrificing readability:

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));

etc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.