gpt4 book ai didi

c# - 嵌套集合的属性上的 EF Core sum 不起作用

转载 作者:行者123 更新时间:2023-12-04 10:19:42 24 4
gpt4 key购买 nike

我的数据库具有以下结构:一个用户可以拥有多个帐户。一个账户可以进行多次转账。

这是 map 配置。我想在我的 DTO 中存储有关每个用户的信息以及他在每个帐户中的总储蓄。 (下面的代码代表整个配置的一部分)。

this.CreateMap<User, UserTestModel>()
.ForMember(
utm => utm.AccountsSavings,
options => options.MapFrom(u => u.Accounts
.Select(a => a.Transfers.Sum(t => t.Amount))
.ToList()));

我对数据库的查询(我将 EF Core 3.1.3 与 Sqlite 数据库一起使用)如下所示:
var resultSet = await this._dbContext.Users
.ProjectTo<UserTestModel>(this.Mapper.ConfigurationProvider)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);

但是抛出以下异常。

*

System.InvalidOperationException : The LINQ expression 'DbSet .Where(t => EF.Property>((EntityShaperExpression: EntityType: Account ValueBufferExpression: (ProjectionBindingExpression: EmptyProjectionMember) IsNullable: False ), "Id") != null && EF.Property>((EntityShaperExpression: EntityType: Account ValueBufferExpression: (ProjectionBindingExpression: EmptyProjectionMember) IsNullable: False ), "Id") == EF.Property>(t, "AccountId")) .Sum(t => t.Amount)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().



*

这是我的代码的问题,还是我目前使用的一些框架(AutoMapper 或 EF Core)的问题?

编辑 1:

我决定尝试从 User 手动收集该信息。实体,但该代码导致相同的异常,这意味着它不是 Automapper 的错:
var resultSet = await this._dbContext.Users
.Select(u => u.Accounts.Select(a => a.Transfers.Sum(t => t.Amount)).ToList())
.ToListAsync(cancellationToken)
.ConfigureAwait(false);

编辑 2:

在 EntityFrameworkCore 的 GitHub 上创建问题: https://github.com/dotnet/efcore/issues/20455

最佳答案

我能够使用 SQLite 提供程序和 Amount 重现它类型是 decimal (适用于 SqlServer 提供程序)。
所以你似乎正在点击以下 SQLite Query Limitations来自 EF Core 文档:

SQLite doesn't natively support the following data types. EF Core can read and write values of these types, and querying for equality (where e.Property == value) is also supported. Other operations, however, like comparison and ordering will require evaluation on the client.

  • DateTimeOffset
  • Decimal
  • TimeSpan
  • UInt64

作为解决方法,请考虑从文档中获取建议:

The Decimal type provides a high level of precision. If you don't need that level of precision, however, we recommend using double instead. You can use a value converter to continue using decimal in your classes.


带 sample
modelBuilder.Entity<MyEntity>()
.Property(e => e.DecimalProperty)
.HasConversion<double>();

关于c# - 嵌套集合的属性上的 EF Core sum 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60916103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com