簡體   English   中英

在LINQ查詢中使用內置的sql函數?

[英]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: 如何:調用自定義數據庫函數

  • 在數據庫中創建自定義函數。
  • 在.edmx文件的商店模式定義語言(SSDL)中聲明一個函數。 函數的名稱必須與數據庫中聲明的函數的名稱相同。
  • 將相應的方法添加到應用程序代碼中的類,並將EdmFunctionAttribute應用於方法請注意,屬性的NamespaceName和FunctionName參數分別是概念模型的命名空間名稱和概念模型中的函數名稱。 LINQ的函數名稱解析區分大小寫。
  • 在LINQ to Entities查詢中調用該方法。

添加了自定義功能

[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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM