3

かなり大きな linq-to-nhibernate クエリがあります。ここで、パラメーターを渡す必要がある t-sql で記述されたユーザー定義関数に基づいてフィルターを追加する必要があります。私の場合、ユーザーが入力した zipcode を渡し、それを t-sql 関数に渡して、この zip からの距離でフィルター処理する必要があります。これは可能ですか、それとも 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 に答える