Linq To NHibernate Plus, a user-defined feature

I have a pretty big linq-to-nhibernate request. Now I need to add a filter based on a custom function written in t-sql with which I need to pass parameters. In my case, I need to pass in the zip code that the user enters and passes it to the t-sql functions to filter by distance from this zip code. Is this possible, or do I need to rewrite my request using ICriteria api?

+3
source share
1 answer

I found a solution:

Notice the NHibernate (nquery) query that 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));
        }
+3
source

Source: https://habr.com/ru/post/1727379/


All Articles