代码之家  ›  专栏  ›  技术社区  ›  toxaq

通过用户定义的函数输出进行Nhibernate过滤

  •  4
  • toxaq  · 技术社区  · 16 年前

    我是NHibernate的新手,到目前为止一切都很顺利,但我遇到了一个问题,我不确定如何着手解决。基本上,我需要根据用户定义函数的输出进行过滤。如果我是用SQL写的,我会这样写:

    declare @Latitude decimal
    declare @Longitude decimal
    declare @radius int
    
    set @Latitude = -118.4104684 
    set @Longitude = 34.1030032
    
    select  * 
    from    store
    where   dbo.CalculateDistance([Latitude], [Longitude], @Latitude, @Longitude) < @radius
    

    我已经看到了我认为不合适的formula属性,命名查询和创建自己的方言扩展的示例(这似乎有点过分了)。我本以为有更直接的方法,但我似乎找不到一个好的例子。

    2 回复  |  直到 14 年前
        1
  •  7
  •   Darin Dimitrov    16 年前

    您可以在hibernate查询中使用SQL表达式。假设你已经映射了一个 Store 键入您可以编写以下查询:

    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>();
    
        2
  •  4
  •   Asbjørn Ulsberg    16 年前

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

    注册它,就像这样:

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

    session.CreateQuery() .