【发布时间】:2012-07-24 16:46:15
【问题描述】:
是否可以在 LINQ 查询中使用像 user_name() 这样的内置 sql 函数?如果没有,我可以用别的东西吗?
【问题讨论】:
是否可以在 LINQ 查询中使用像 user_name() 这样的内置 sql 函数?如果没有,我可以用别的东西吗?
【问题讨论】:
这取决于提供者。例如,在针对 SQL Server 的 LINQ to Entities 中,您可以使用 SqlFunctions - 它有一个 UserName 方法,对应于 Transact-SQL 中的 USER_NAME()。 (还有很多其他的方法和属性,对于当前用户,比如CurrentUser属性就可以了。)
【讨论】:
DataContext dataContext = new DataContext("conn string"); Table<Customer> customers = dataContext.GetTable<Customer>(); var b = from c in customers where SqlFunctions.CharIndex("r", c.Name) == 0 select c.Name; var v = b.ToString(); 这导致最后一行出现以下错误 - Method 'System.Nullable``1[System.Int32] CharIndex(System.String, System.String)' has no supported translation to SQL.
@jon Skeet 答案的扩展
SqlFunctions Class - 提供公共语言运行时 (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 Method
使用SqlFunctions.UserName ()
这里是 MSDN: How to: Call Custom Database Functions
新增自定义功能
[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)
};
【讨论】:
DataContext 类做一个简单的 linq to sql。这种方法不涉及任何 EDMX 文件。我将如何使用您的方法来调用我的用户定义的 sql server 函数?