linq2db“无法转换为sql”错误

时间:2016-04-06 19:45:01

标签: c# linq linq2db

我正在使用Linq2db和自定义服务器端功能:

[Sql.Function(Name = "UniqueValue", ServerSideOnly = true)]
public static int? UniqueValue( Expression<Func<ModelClass, string>> arg) {
            throw new NotSupportedException();
}

然后我尝试在带有分组的linq查询中使用它:

var query = from a in context.data
                    group a by a.field1 into newgroup
                    select new {final = UniqueValue(row => row.field2) };

然后我得到“row =&gt; row.field2”无法转换为SQL。“运行时出错。

我使用SqlLite作为db,这是自定义函数:

[SQLiteFunction(Name = "UniqueValue", Arguments = 1, FuncType = FunctionType.Aggregate)]
    public class UniqueValue : SQLiteFunction {
        public override void Step(object[] args, int stepNumber, ref object contextData) {

        }

        public override object Final(object contextData) {
            return null;
        }
    }

有谁知道我如何才能使自定义服务器端功能与分组一起使用?

1 个答案:

答案 0 :(得分:0)

在1.9.0版中添加了对linq2db中的自定义聚合函数的支持。您需要像这样将函数定义为自定义聚合:

[Sql.Function("UniqueValue", ServerSideOnly = true, IsAggregate = true, ArgIndices = new[]{0})]
public static TResult UniqueValue<TSource, TResult>(this IEnumerable<TSource> src, Expression<Func<TSource, TResult>> value)
    => throw new NotSupportedException();

并使用:

var query = from a in context.data
    group a by new a.field1 into newgroup
    select new { final = newgroup.UniqueValue(row => row.field2) };