开发者

Linq To NHibernate Plus sql user defined function

开发者 https://www.devze.com 2022-12-16 00:10 出处:网络
I have a rather large linq-to-nhibernate query.I now need to add a filter based on auser-defined function written in t-sql that i have to pass parameters into.In my case, I need to pass in a zipcode t

I have a rather large linq-to-nhibernate query. I now need to add a filter based on a user-defined function written in t-sql that i have to pass parameters into. In my case, I need to pass in a zipcode that the user types in and pass it to the t-sql function to fil开发者_开发技巧ter by distance from this zip. Is this possible, or do i need to rewrite my query using the ICriteria api?


i did find a solution:

Note the NHibernate query (nquery) which has RegisterCustomAction:

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

精彩评论

暂无评论...
验证码 换一张
取 消