Nhibernate filtering by user defined function output

前端 未结 2 1171
离开以前
离开以前 2021-01-01 05:08

I\'m reasonably new to NHibernate and everything has been going pretty well so far but I\'ve come across a problem I\'m not exactly sure of how to go about solving. Basicall

相关标签:
2条回答
  • 2021-01-01 05:36

    Creating custom dialect extensions is rather easy:

    public class CustomFunctionsMsSql2005Dialect : MsSql2005Dialect 
    { 
       public CustomFunctionsMsSql2005Dialect() 
       { 
          RegisterFunction("calculatedistance",
                           new SQLFunctionTemplate(NHibernateUtil.Int32,
                                                   "CalculateDistance(?1, ?2, ?3, ?4)"));
       }
    }
    

    Register it, like so:

    <property name="hibernate.dialect">
      CustomFunctionsMsSql2005Dialect, MyAssembly
    </property>
    

    Now you can use it like any other HQL function in queries like those created with session.CreateQuery().

    0 讨论(0)
  • 2021-01-01 05:43

    You could use SQL expression in your hibernate queries. Assuming you've mapped a Store type you could write the following query:

    var result = session
        .CreateCriteria<Store>()
        .Add(Expression.Sql(
            "dbo.CalculateDistance({alias}.Latitude, {alias}.Longitude, ?, ?) < ?",
            new object[] { 
                -118.4104684d, 
                34.1030032d, 
                100 
            },
            new IType[] { 
                NHibernateUtil.Double, 
                NHibernateUtil.Double, 
                NHibernateUtil.Int32 
            }
        ))
        .List<Store>();
    
    0 讨论(0)
提交回复
热议问题