我是 Entity Framework 的新手,我不断收到 Entity Framework 中的 EntityCommandCompilationException
specified method not supported
。我不明白为什么会引发此异常。
我已经使用发布的指南为我的 MySQL 服务器 5.7 安装创建了自定义 UDF 聚合函数 my_Func()
here.它就像任何普通的聚合函数一样工作,例如Sum() 会起作用。即我可以执行语句 select my_Func(Column4) from db.table
并将所需结果作为 double
返回。我已经测试过了,它可以在 MySQL 服务器上运行。我希望能够在 linq to entities 查询中使用这个方法,为了做到这一点,我做了以下事情。
using (var context = new dbEntities())
{
var results = from items in context.table
group items by new
{ items.Column1, items.Column2 } into groupingItem
select new OutputType()
{
GroupedResult = groupingItem.OrderBy(x => x.Column3).Select(x => x.Column4).my_Func()
};
}
我创建了一个包含该方法的静态类。
public static class ModelDefinedFunctions
{
[DbFunction("dbModel.Store", "my_Func")]
public static double my_Func(this IEnumerable<double> items)
{
throw new NotSupportedException("Direct calls are not supported.");
}
}
在 .edmx 文件中我手动添加了以下标签
<Function Name="my_Func" ReturnType="double" Aggregate="true"
BuiltIn="false" NiladicFunction="false"
IsComposable="true" ParameterTypeSemantics="AllowImplicitConversion" Schema="db">
<Parameter Name="value" Type="Collection(double)" Mode="In" />
</Function>
最佳答案
使用以下代码查看 Entity Framework 创建的 SQL,然后尝试直接在您的数据库上运行它。
IQueryable query = from x in appEntities
where x.id = 32
select x;
var sql = ((System.Data.Objects.ObjectQuery)query).ToTraceString();
或在 EF6 中:
var sql = ((System.Data.Entity.Core.Objects.ObjectQuery)query)
.ToTraceString();
(从 How do I view the SQL generated by the Entity Framework? 窃取)
很可能 EF 没有生成您认为的查询。您可能会考虑在 StringBuilder 中构建查询并通过 EF 执行它,如下所示:
using (var db = new DbEntity())
{
var sqlStatement = new StringBuilder();
sqlStatement.AppendFormat("SELECT * FROM TABLENAME WHERE ID = '{0}' ", id);
var result = db.ExecuteStoreQuery<MyTableObject>(sqlStatement.ToString()).ToList();
}
关于c# - EntityCommandCompilationException 指定的方法不支持 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39124733/