c# - 有条件地添加限制

标签 c# nhibernate

我有非常复杂的标准。让我们看看以下标准:

         new List < ICriterion > {
            Restrictions.Not(Restrictions.Eq("Name", user.Name)),
            Restrictions.Or(
               Restrictions.And(
                  Restrictions.And(                 
                     Restrictions.Eq("Status", user.Status))
                     ...
                ))
                ...
         };

但我需要根据一项设置有条件地添加一个限制。

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

如何避免这种重复?

最佳答案

您可以将条件作为变量取出并使用它,例如,

         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   
                        ...
                 };

关于c# - 有条件地添加限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32471235/

相关文章:

c# - Package.Open()异常: Access to path is denied

c# - 拒绝访问 .tmp 路径

oracle - Nhibernate 与 oracle - 主键增量的最佳方式

c# - NHibernate 列表索引映射到不可空的数据库列

nhibernate - NHibernate 工具

c# - 如何将 CaSTLe Activerecord 转换为纯 NHibernate 或 Fluent NHibernate?

c# - 在 C# 中停止执行程序

c# - 从 FileSystemWatcher 事件更新列表框

c# - 需要有关游戏设计/结构的建议

c# - nhibernate 不级联删除 child