borisdj / EFCore.BulkExtensions

Entity Framework EF Core efcore Bulk Batch Extensions with BulkCopy in .Net for Insert Update Delete Read (CRUD), Truncate and SaveChanges operations on SQL Server, PostgreSQL, MySQL, SQLite

Home Page:https://codis.tech/efcorebulk

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

MySQL error when using BatchUpdateAsync() method

MayGodBlessYouAMen opened this issue · comments

My project environment:
mysql8, .net8, efcore8, EFCore.BulkExtensions 8.0.2
The code I use like this:
dbContext.Users.Where(x => x.State == 0).BatchUpdateAsync(x => new User { State = 1 });
error message:
"Unable to cast object of type 'Microsoft.Data.SqlClient.SqlParameter' to type 'MySqlConnector.MySqlParameter'."

When I looked at the source code of the EFCore.BulkExtensions project, I found that the method does not support MySQL:
public static (string, List<object>) GetSqlUpdate<T>(IQueryable<T> query, DbContext context, Type type, Expression<Func<T, T>> expression)

var databaseType = SqlAdaptersMapping.GetDatabaseType();
        if (databaseType == SqlType.PostgreSql)
        {
           ...
            sqlParameters = npgsqlParameters;
        }
  
        return (resultQuery, sqlParameters);

Another method supports MySQL, but I don’t want to use it because I use the Expression parameter:
public static (string, List<object>) GetSqlUpdate(IQueryable query, DbContext context, Type type, object? updateValues, List<string>? updateColumns)

        var databaseType = SqlAdaptersMapping.GetDatabaseType();
        if (databaseType == SqlType.PostgreSql)
        {
             ...
            sqlParameters = npgsqlParameters;
        }
        else if (databaseType == SqlType.MySql)
        {
            ...
            sqlParameters = mysqlParameters;
        }

        return (resultQuery, sqlParameters);

Can you add MySQL support for the method
BatchUtil.GetSqlUpdate<T>(IQueryable<T> query, DbContext context, Type type, Expression<Func<T, T>> expression)

Code refactored with the fix, will be published with next nuget release.

Also have you tried new EF native method ExecuteUpdate.
Batch ops are deprecated, Lib focus in mainly on Bulk.