[英]Using built-in sql functions in a LINQ query?
是否可以在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: 如何:調用自定義數據庫函數
添加了自定義功能
[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)
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.