Reputation: 33
Is it possible to use buillt-in sql functions like user_name() in a LINQ query? If not, can I use something else?
Upvotes: 3
Views: 23605
Reputation: 176886
Extension to @jon Skeet answer
SqlFunctions Class - Provides common language runtime (CLR) methods that call functions in the database in LINQ to Entities queries.
How to use
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);
}
}
For : SqlFunctions.UserName Method
use SqlFunctions.UserName ()
Here is MSDN : How to: Call Custom Database Functions
Added Custom function
[EdmFunction("SchoolModel.Store", "AvgStudentGrade")]
public static decimal? AvgStudentGrade(int studentId)
{
throw new NotSupportedException("Direct calls are not supported.");
}
In Linq query
var students = from s in context.People
where s.EnrollmentDate != null
select new
{
name = s.LastName,
avgGrade = AvgStudentGrade(s.PersonID)
};
Upvotes: 4
Reputation: 1499770
It depends on the provider. For example, in LINQ to Entities against SQL Server you can use SqlFunctions
- which has a UserName
method which corresponds to USER_NAME()
in Transact-SQL. (There are many other methods and properties. For the current user, you can just use the CurrentUser
property, for example.)
Upvotes: 7