Reputation: 9288
I have very complex criteria. Let's see the following criteria:
new List < ICriterion > {
Restrictions.Not(Restrictions.Eq("Name", user.Name)),
Restrictions.Or(
Restrictions.And(
Restrictions.And(
Restrictions.Eq("Status", user.Status))
...
))
...
};
but I need to add one restriction conditionally in depend on one setting.
if(Setting.SomeSettings)
{
new List < ICriterion > {
Restrictions.Not(Restrictions.Eq("Name", user.Name)),
Restrictions.Or(
Restrictions.And(
Restrictions.And(
**//new restriction**
Restrictions.Eq("Some", user.Some))
Restrictions.Eq("Status", user.Status))
...
))
...
};
}
else
{
new List < ICriterion > {
Restrictions.Not(Restrictions.Eq("Name", user.Name)),
Restrictions.Or(
Restrictions.And(
Restrictions.And(
Restrictions.Eq("Status", user.Status))
...
))
...
};
}
How to avoid this duplication?
Upvotes: 2
Views: 97
Reputation: 6054
You can take out the condition as a variable and use it, something like,
ICriterion criterion;
if(Setting.SomeSettings)
{
criterion = Restrictions.And(
**//new restriction**
Restrictions.Eq("Some", user.Some))
Restrictions.Eq("Status", user.Status))
...
));
}
else
{
criterion = Restrictions.And(
Restrictions.And(
Restrictions.Eq("Status", user.Status))
...
));
}
new List < ICriterion > {
Restrictions.Not(Restrictions.Eq("Name", user.Name)),
Restrictions.Or(
Restrictions.And(
criterion
...
};
Upvotes: 1