我有一个表值函数,我想将其用作 IQueryable
在 LINQ 语句中。我在我的 DbContext
中创建了以下内容类:
[DbFunction("dbo","MyTableValuedFunction")]
public virtual IQueryable<MyClass> MyFunction(string keyword)
{
var keywordsParam = new System.Data.Entity.Core.Objects.ObjectParameter("keywords", typeof(string))
{
Value = keyword
};
return (this as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext
.CreateQuery<MyClass>("dbo.MyTableValuedFunction(@keywords)", keywordsParam);
}
dbo.MyTableValuedFunction(@keywords)
的结果匹配现有类“MyClass
”。我想如何使用此功能的示例:
MyClass example = (from a in dbContext.MyClass
join b in dbContext.MyFunction("exampleKeyword")
on a.Id equals b.Id
join c in dbContext.MyOtherClass
on a.SomeId equals c.Id
select a);
...但是枚举这个 IEnumerable
抛出异常:
'dbo.MyTableValuedFunction' cannot be resolved into a valid type or function.
我曾尝试将函数缩减为一列,并将类型更改为 <int>
,但这不起作用,所以我不确定这里发生了什么;好像没有正确找到/识别/使用 TVF?
我也试过关注 https://weblogs.asp.net/Dixin/EntityFramework.Functions#Table-valued_function偶尔会有一些细微的差别,我用以下方法创建函数:
[Function(FunctionType.TableValuedFunction, "MyTableValuedFunction", Schema = "dbo")]
...但我遇到了完全相同的问题。
最佳答案
首先,如果您使用 this扩展,你应该根据你的代码编写如下代码:
[DbFunction("dbo","MyTableValuedFunction")]
public virtual IQueryable<MyClass> MyFunction(string keyword)
{
var keywordsParam = new System.Data.Entity.Core.Objects.ObjectParameter("keywords", typeof(string))
{
Value = keyword
};
return (this as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext
.CreateQuery<MyClass>("[Your DbContext Name].MyFunction(@keywords)", keywordsParam);
}
根据扩展代码,EF使用约定将C#语法翻译成sql语法。因此,您应该首先按照提到的链接在 dbContext 中注册您的函数。
关于c# - 在 EF 中作为 IQueryable 的表值函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42365555/