3

我有一个相当大的 linq-to-nhibernate 查询。我现在需要添加一个基于用 t-sql 编写的用户定义函数的过滤器,我必须将参数传递给该过滤器。就我而言,我需要传入用户输入的邮政编码并将其传递给 t-sql 函数,以按与该邮政编码的距离进行过滤。这可能吗,还是我需要使用 ICriteria api 重写我的查询?

4

1 回答 1

3

我确实找到了解决方案:

请注意具有 RegisterCustomAction 的 NHibernate 查询 (nquery):

private void CallZipSqlFunction(ListingQuerySpec spec, IQueryable<Listing> query)
        {

            var nQuery = query as NHibernate.Linq.Query<Listing>;

            //todo: find some way to paramaterize this or use linq-to-nh and not criteria to call the function
            // so i don thave to check for escape chars in zipcode
            if (spec.ZipCode.Contains("'"))
                throw new SecurityException("invalid character");

            //yuck!
            var functionString = "dbo.GetDistanceForListing('" + spec.ZipCode + "',{alias}.ID) as Distance";
            //create a projection representing the function call
            var distance = Projections.SqlProjection(functionString, new[] { "Distance" }, new IType[] { NHibernateUtil.String });

            //create a filter based on the projection
            var filter = Expression.Le(distance, spec.ZipCodeRadius.Value);

            //add the distance projection as order by
            nQuery.QueryOptions.RegisterCustomAction(x => x.AddOrder(Order.Asc(distance)));

            //add teh distance filter
            nQuery.QueryOptions.RegisterCustomAction(x => x.Add(filter));
        }
于 2010-02-18T22:32:10.970 回答