gpt4 book ai didi

tsql - Linq To NHibernate Plus sql 用户定义函数

转载 作者:行者123 更新时间:2023-12-01 14:59:37 24 4
gpt4 key购买 nike

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

最佳答案

我确实找到了解决方案:

注意具有 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));
}

关于tsql - Linq To NHibernate Plus sql 用户定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2007379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com