我很难让它发挥作用。我正在尝试在 IQueryable 上使用以下过滤器助手进行半径搜索。在 RadiusSearch 应用之前,还有一组其他过滤器会被应用。顺序应该并不重要,因为目标是让查询延迟到 ToList() 操作。
public static IQueryable<ApiSearchCommunity> RadiusSearch(this IQueryable<ApiSearchCommunity> communities)
{
var centerLatitude = 30.421278;
var centerLongitude = -97.426261;
var radius = 25;
return communities.Select(c => new ApiSearchCommunity()
{
CommunityId = c.CommunityId,
City = c.City,
//Distance = c.GetArcDistance(centerLatitude, centerLongitude, c.Latitude, c.Longitude, radius)
});
}
我能否以某种方式编写一个像上面的 GetArcDistance 这样的帮助器,然后在 SQL 上调用 UDF?我要生成的查询如下
SELECT
comms.community_id,
comms.city,
comms.distance
FROM (
SELECT
c.community_id,
c.city,
dbo.udf_ArcDistance(
30.421278,-97.426261,
c.community_latitude,
c.community_longitude
) AS distance
FROM communities c) AS comms
WHERE comms.distance <= 25
ORDER BY comms.distance
最佳答案
好的,我想我理解了这个问题 - 它的要点是您希望能够调用 SQL UDF 作为 Linq to Entities 查询的一部分。
这是如果您首先使用数据库或模型:
这篇文章解释了如何去做:http://msdn.microsoft.com/en-us/library/dd456847(VS.100).aspx
总而言之,您首先需要在 xml 编辑器中编辑您的 edmx 文件,在 edmx:StorageModels >> Schema 部分您需要指定到您的 sql udf 的映射,例如
<Function Name="SampleFunction" ReturnType="int" Schema="dbo">
<Parameter Name="Param" Mode="In" Type="int" />
</Function>
然后你需要在某处创建一个带有 EdmFunction 属性的静态函数,像这样:
public static class ModelDefinedFunctions
{
[EdmFunction("TestDBModel.Store", "SampleFunction")]
public static int SampleFunction(int param)
{
throw new NotSupportedException("Direct calls are not supported.");
}
}
此方法将在查询时由 Entity Framework 映射到 UDF。第一个属性参数是商店 namespace ——您可以在 Schema 元素上的 edmx xml 文件中找到它(查找 namespace )。第二个参数是 udf 的名称。
你可以这样调用它:
var result = from s in context.UDFTests
select new
{
TestVal = ModelDefinedFunctions.SampleFunction(22)
};
希望这对您有所帮助。
关于c# - 在 LINQ 查询中调用 SQL 用户定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20131632/