C# SQL级别的函数可以用于LINQ到实体查询吗?
我希望我能将LINQ写入调用其他函数的实体查询:C# SQL级别的函数可以用于LINQ到实体查询吗?,c#,entity-framework,C#,Entity Framework,我希望我能将LINQ写入调用其他函数的实体查询: from c in context.Widgets where MyFunc(c.name) select c 这会导致错误,因为表达式显然无法转换为调用MyFunc的TSQL 嗯,我在想,除非MyFunc是一个用户定义的函数,或者(我认为更好)是一个SQL/CLR函数 那么这是可能的,而且是建议的吗 如果不可能,我是否希望此功能有效,并且ADO.NET的未来可能会解决此问题?EF致力于将.NET类与数据库的结构同步,最好是在数据库是哑的且所有
from c in context.Widgets
where MyFunc(c.name)
select c
这会导致错误,因为表达式显然无法转换为调用MyFunc的TSQL
嗯,我在想,除非MyFunc是一个用户定义的函数,或者(我认为更好)是一个SQL/CLR函数
那么这是可能的,而且是建议的吗
如果不可能,我是否希望此功能有效,并且ADO.NET的未来可能会解决此问题?EF致力于将.NET类与数据库的结构同步,最好是在数据库是哑的且所有逻辑都位于类中的情况下 但是,您可以映射到函数和存储过程—这有点技术性,需要解释(要容易得多)—让我为您找到一些链接 这里有一个不好的方法:
// Query that calls the OrderTotal function to recalculate the order total.
string queryString = @"USING Microsoft.Samples.Entity;
FUNCTION OrderTotal(o SalesOrderHeader) AS
(o.SubTotal + o.TaxAmt + o.Freight)
SELECT [order].TotalDue AS currentTotal, OrderTotal([order]) AS calculated
FROM AdventureWorksEntities.SalesOrderHeaders AS [order]
WHERE [order].Contact.ContactID = @customer";
int customerId = 364;
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(queryString, context);
query.Parameters.Add(new ObjectParameter("customer",customerId));
foreach (DbDataRecord rec in query)
{
Console.WriteLine("Order Total: Current - {0}, Calculated - {1}.",
rec[0], rec[1]);
}
}
//调用OrderTotal函数以重新计算订单总额的查询。
使用Microsoft.Samples.Entity的字符串queryString=@;
函数OrderTotal(o SalesOrderHeader)作为
(o.小计+o.税额+o.运费)
选择[order].TotalDue作为currentTotal,OrderTotal([order])作为计算结果
从AdventureWorksEntities.SalesOrderHeaders中选择[order]
其中[order].Contact.ContactID=@customer”;
int customerId=364;
使用(AdventureWorksEntities)上下文=
新建AdventureWorksEntities())
{
ObjectQuery=新的ObjectQuery(查询字符串,上下文);
添加(新的ObjectParameter(“customer”,customerId));
foreach(查询中的DbDataRecord rec)
{
WriteLine(“订单总数:当前-{0},计算-{1}.”,
rec[0],rec[1]);
}
}
An以下是正确操作的方法:
// Query that calls the OrderTotal function to recalculate the order total.
string queryString = @"USING Microsoft.Samples.Entity;
FUNCTION OrderTotal(o SalesOrderHeader) AS
(o.SubTotal + o.TaxAmt + o.Freight)
SELECT [order].TotalDue AS currentTotal, OrderTotal([order]) AS calculated
FROM AdventureWorksEntities.SalesOrderHeaders AS [order]
WHERE [order].Contact.ContactID = @customer";
int customerId = 364;
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(queryString, context);
query.Parameters.Add(new ObjectParameter("customer",customerId));
foreach (DbDataRecord rec in query)
{
Console.WriteLine("Order Total: Current - {0}, Calculated - {1}.",
rec[0], rec[1]);
}
}
您应该在数据库中创建一个用户定义的函数
MyFunc
,并手动将其“导入”到您的上下文中(edmx,所以先导入数据库),既可以是XML,也可以是上下文类之外的部分类中的存根。此处描述了该过程:
(请注意,“StorageNamespace”是您在XML文件中