Calling a SQL Function from your Entity Framework LINQ query is easy thanks to the availability of the SqlFunctions class. This class provides methods that call functions in the database in LINQ to Entities queries.
Here is an example where I call the DatePart function:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var chartData = from log in _contextProvider.Context.Logs | |
group log by new | |
{ | |
ApplicationName=log.Application.Name, | |
Year= SqlFunctions.DatePart("Year", log.Timestamp), | |
Month= SqlFunctions.DatePart("Month",log.Timestamp) | |
} | |
into logsPerApplication | |
select new | |
{ | |
Count = logsPerApplication.Count(), | |
logsPerApplication.Key.ApplicationName, | |
logsPerApplication.Key.Year, | |
logsPerApplication.Key.Month | |
}; | |