Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

Summation error (Sum) in Entity Framework and MySQL

I use MySQL & Entity Framework (NET 5 / NET Core 3.1). I have a ‘Users’ table created based on the ‘User’ 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. Why can't I sum fields like short or byte?!

I use for NET Core 3.1:

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

I use for NET 5:

  • Microsoft.EntityFrameworkCore 5.0.2
  • MySql.EntityFrameworkCore 5.0.0-m8.0.23
question from:https://stackoverflow.com/questions/65858348/summation-error-sum-in-entity-framework-and-mysql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It would be nice to do this, but there isn't a translation for Convert functions to (generic) 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...