在LINQ查询中使用内置的sql函数?

是否可以在LINQ查询中使用像user_name()这样的buillt-in sql函数? 如果没有,我可以使用其他东西吗?

这取决于提供商。 例如,在针对SQL Server的LINQ to Entities中,您可以使用SqlFunctions – 它具有与Transact-SQL中的USER_NAME()对应的UserName方法。 (还有许多其他方法和属性。例如,对于当前用户,您可以使用CurrentUser属性。)

编辑

扩展到@jon Skeet的答案

SqlFunctions类 – 提供公共语言运行时(CLR)方法,用于在LINQ to Entities查询中调用数据库中的函数。

如何使用

 using (AdventureWorksEntities AWEntities = new AdventureWorksEntities()) { // SqlFunctions.CharIndex is executed in the database. var contacts = from c in AWEntities.Contacts where SqlFunctions.CharIndex("Si", c.LastName) == 1 select c; foreach (var contact in contacts) { Console.WriteLine(contact.LastName); } } 

对于: SqlFunctions.UserName方法使用SqlFunctions.UserName ()


这是MSDN: 如何:调用自定义数据库函数

  • 在数据库中创建自定义函数。
  • 在.edmx文件的商店架构定义语言(SSDL)中声明一个函数。 函数的名称必须与数据库中声明的函数的名称相同。
  • 将相应的方法添加到应用程序代码中的类,并将EdmFunctionAttribute应用于方法请注意,属性的NamespaceName和FunctionName参数分别是概念模型的命名空间名称和概念模型中的函数名称。 LINQ的函数名称解析区分大小写。
  • 在LINQ to Entities查询中调用该方法。

添加了自定义function

 [EdmFunction("SchoolModel.Store", "AvgStudentGrade")] public static decimal? AvgStudentGrade(int studentId) { throw new NotSupportedException("Direct calls are not supported."); } 

在Linq查询

 var students = from s in context.People where s.EnrollmentDate != null select new { name = s.LastName, avgGrade = AvgStudentGrade(s.PersonID) };