[英]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 属性是short或byte ,则会出现错误。 Why can't I sum fields like short or byte?!
为什么我不能对短或字节之类的字段求和?!
I use for NET Core 3.1:我用于 NET Core 3.1:
I use for NET 5:我用于 NET 5:
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.