简体   繁体   English

Entity Framework 和 MySQL 中的求和错误(Sum)

[英]Summation error (Sum) in Entity Framework and MySQL

I use MySQL & Entity Framework (NET 5 / NET Core 3.1).我使用 MySQL 和实体框架(NET 5 / NET Core 3.1)。 I have a 'Users' table created based on the 'User' class:我有一个基于“用户”class 创建的“用户”表:

public class User
{
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; } // int!
}

I can sum up the ages of all users:我可以总结一下所有用户的年龄:

var result = dbContext.Users.Sum(s => s.Age); // Ok

But, if the Age property is short or byte , then there will be an error .但是,如果Age 属性shortbyte ,则会出现错误 Why can't I sum fields like short or byte?!为什么我不能对短或字节之类的字段求和?!

I use for NET Core 3.1:我用于 NET Core 3.1:

  • Microsoft.EntityFrameworkCore 3.1.11 Microsoft.EntityFrameworkCore 3.1.11
  • MySql.Data.EntityFrameworkCore 8.0.22 MySql.Data.EntityFrameworkCore 8.0.22

I use for NET 5:我用于 NET 5:

  • Microsoft.EntityFrameworkCore 5.0.2 Microsoft.EntityFrameworkCore 5.0.2
  • MySql.EntityFrameworkCore 5.0.0-m8.0.23 MySql.EntityFrameworkCore 5.0.0-m8.0.23

It would be nice to do this, but there isn't a translation for Convert functions to (generic) SQL:这样做会很好,但没有将函数转换为(通用)SQL 的翻译:

var result = dbContext.Users.Sum(s => Convert.ToInt32(s.Age)); 

This should work instead:这应该起作用:

var result = dbContext.Users
    .Select(x => x.Age) // We only need one field, not the whole user object.
    .ToArray() // Run the SQL and bring over the array of short/byte
    .Sum(); // Client-side Sum method accepts byte or short.

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

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