简体   繁体   English

使用 Entity Framework Core 按类型未知的 JsonDocument 属性分组

[英]Group by JsonDocument's property with unknown type using Entity Framework Core

I'm using Entity Framework Core 3.1.5我正在使用实体框架核心 3.1.5

I'm trying to group entities by some property of JsonDocument , which I don't know its type.我正在尝试按JsonDocument的某些属性对实体进行分组,但我不知道它的类型。 AdditionalData is the JsonDocument property of the entities. AdditionalData是实体的JsonDocument属性。

I need to execute the commands on the database.我需要在数据库上执行命令。

I managed to do it with two restrictions我设法做到了有两个限制

  1. I specified the property's type (with GetInt32)我指定了属性的类型(使用 GetInt32)
  2. The commands were executed on the client and not on the DB.这些命令是在客户端而不是数据库上执行的。
    IEnumerable<MetricEntity> metricEntities = _tenantDbContext.Set<MetricEntity>();
    var ii2 = metricEntities.Where(metric => metric.Name == metricName).GroupBy(e =>
        e.AdditionalData!.RootElement.GetProperty(groupByProperty).GetInt32())
    .Select(entities => new
    {
        Count = entities.Count(), MetType = entities.Key, Ent = entities,
    }).ToList();

I also managed to do it without getting all the entities in the result and with the restriction that the commands were executed on the client and not on the DB.我还设法做到了,没有得到结果中的所有实体,并且限制了命令是在客户端而不是数据库上执行的。

var i2 = _tenantDbContext.Set<MetricEntity>()
.Where(metric => metric.Name == metricName)
.GroupBy(e =>
    e.AdditionalData!.RootElement.GetProperty(groupByProperty).GetString())
.Select(entities => new
{
    Count = entities.Count(), MetType = entities.Key
}).ToList();

But when I'm adding the entities to the result as follow:但是当我将实体添加到结果中时,如下所示:

var i2 = _tenantDbContext.Set<MetricEntity>()
.GroupBy(e =>
    e.AdditionalData!.RootElement.GetProperty(groupByProperty).GetString())
.Select(entities => new
{
    Count = entities.Count(), MetType = entities.Key, ent = entities,
}).ToList();

I'm getting the following exception:我收到以下异常:

System.InvalidOperationException: Processing of the LINQ expression '(GroupByShaperExpression:
KeySelector: ((m.AdditionalData)#>>{(@__groupByProperty_1)}),
ElementSelector:(EntityShaperExpression:
    EntityType: MetricEntity
    ValueBufferExpression:
        (ProjectionBindingExpression: EmptyProjectionMember)
    IsNullable: False
)
)' by 'RelationalProjectionBindingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitNew(NewExpression newExpression)
   at System.Linq.Expressions.NewExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

Each group by query should contain one or more keys and other properties which have aggregating function only in the select statement ( Sum , Count and etc).每个查询group by应包含一个或多个和其他属性,这些键和其他属性仅在 select 语句( SumCount等)中具有聚合 function 。 EF tryed to convert LINQ to SQL query and throws the exception due no internal checks. EF 尝试将 LINQ 转换为 SQL 查询并由于没有内部检查而引发异常。

There is a workaround:有一个解决方法:

Evaluate table data before GroupBy .GroupBy之前评估表数据。 The following code loads all MetricEntities and groups it in c# code:以下代码加载所有MetricEntities并将其分组到 c# 代码中:

var i2 = _tenantDbContext.MetricEntities
.AsEnumerable()
.GroupBy(e =>
    e.AdditionalData!.RootElement.GetProperty(groupByProperty).GetString())
.Select(entities => new
{
    Count = entities.Count(), MetType = entities.Key, ent = entities,
}).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM