how to user year() and month() functions in NH Criteria API?

后端 未结 3 2139
轻奢々
轻奢々 2020-12-13 22:44

I need to use year() and month() functions in Criteria API to be able to express a business filter constrain. Expressions like

cri.Add(Expression.Ge(\"year(         


        
3条回答
  •  悲&欢浪女
    2020-12-13 23:08

    It's possible to achieve this using Projections.SQLFunction. Working solution:

    ISQLFunction sqlAdd = new VarArgsSQLFunction("(", "+", ")");
    ISQLFunction sqlMultiply = new VarArgsSQLFunction("(", "*", ")");
    
    var ym = Year.Value * 100 + Month.Value;
    var dateFromMonthProj = Projections.SqlFunction("month", NHibernateUtil.Int32, Projections.Property("PurchaseDuration.DateFrom"));
    var dateFromYearProj = Projections.SqlFunction("year", NHibernateUtil.Int32, Projections.Property("PurchaseDuration.DateFrom"));
    var dateToMonthProj = Projections.SqlFunction("month", NHibernateUtil.Int32, Projections.Property("PurchaseDuration.DateTo"));
    var dateToYearProj = Projections.SqlFunction("year", NHibernateUtil.Int32, Projections.Property("PurchaseDuration.DateTo"));
    var calculatedYMFrom = Projections.SqlFunction(sqlAdd, NHibernateUtil.Int32, Projections.SqlFunction(sqlMultiply, NHibernateUtil.Int32, dateFromYearProj, Projections.Constant(100)), dateFromMonthProj);
    var calculatedYMTo = Projections.SqlFunction(sqlAdd, NHibernateUtil.Int32, Projections.SqlFunction(sqlMultiply, NHibernateUtil.Int32, dateToYearProj, Projections.Constant(100)), dateToMonthProj);
    cri.Add(Restrictions.Le(calculatedYMFrom, ym));
    cri.Add(Restrictions.Ge(calculatedYMTo, ym));
    

提交回复
热议问题