LINQ to SQL:无法在LINQ查询中使用SQL Server UDF

我在做LINQ到Sql。 为了获得良好的性能,我正在尝试过滤SQL Server端本身的一些记录。 所以我想在我的数据库中使用用户定义的函数(UDF) GiveWordCount 。 基于这篇文章,我正在尝试在C#端使用该UDF。

声明一个虚函数体,以便C#代码可以编译:

 [Function(Name = "dbo.GiveWordCount", IsComposable = true)] public static int GiveWordCount([Parameter(Name="@inputValue",DbType="nvarchar(4000)")]string inputValue) { throw new NotSupportedException("Direct calls are not supported."); } 

然后我在LINQ查询中调用此函数,如下所示。 在最终SQL查询被触发到数据库之前,调用’GiveWordCount’函数应该由LINQ转换为Sql提供程序到等效的内置sql server函数。 相反,它会导致错误:

方法’Int32 GiveWordCount(System.String)’没有支持的SQL转换。

这是我的主要function:

 static void Main(string[] args) { DataContext dataContext = new DataContext("data source=.;initial catalog=businessLinqToSql;integrated security=True;MultipleActiveResultSets=True"); Table customers = dataContext.GetTable(); IEnumerable b = customers.Where(customer => GiveWordCount(customer.Name)  x.Name); foreach (string element in b) Console.WriteLine(element); } 

这是我的客户类:

  [Table] public class Customer { [Column] public string Name { get; set; } } 

我认为该方法需要在具有与现有Linq to Sql DataContext相同的Namespace和Class名称的部分类中。 如果右键单击dbml文件datacontext.dbml => View Code ,它将为您生成空的分部类。

例如,向ISNUMERIC SQL函数添加映射

 using System.Data.Linq.Mapping; namespace SameNamespaceAsDataContext { partial class SameClassnameAsDataContext { [Function(Name = "ISNUMERIC", IsComposable = true)] public int IsNumeric(string input) { throw new NotImplementedException(); // this won't get called } } } 

然后按如下方式调用该方法:

 IQueryable results = MyDataContext.Table.Select(x => IsNumeric(x.Column));