System.TypeLoadException: Method 'Create' in type 'MySql.Data.EntityFrameworkCore.Query.Internal.MySQLSqlTranslatingExpressionVisitorFactory'

Viewed 16123

I'm trying to add a new user to the database with the following code:

public async void SeedUsers(){
    int count=0;
    if(count>0){
        return;
    }
    else{
        string email="jujusafadinha@outlook.com.br";
        _context.Add(new User{LoginEmail=email});  
        await _context.SaveChangesAsync();  
    }
}

But it keeps giving me the following error:

System.TypeLoadException: Method 'Create' in type 'MySql.Data.EntityFrameworkCore.Query.Internal.MySQLSqlTranslatingExpressionVisitorFactory' from >assembly 'MySql.Data.EntityFrameworkCore, Version=8.0.22.0, Culture=neutral, >PublicKeyToken=c5687fc88969c44d' does not have an implementation. at MySql.Data.EntityFrameworkCore.Extensions.MySQLServiceCollectionExtensions.AddEntityFrameworkMySQL(IServ>iceCollection services) at MySql.Data.EntityFrameworkCore.Infrastructure.Internal.MySQLOptionsExtension.ApplyServices(IServiceColle>ction services) at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.ApplyServices(IDbContextOptions >options, ServiceCollection services) at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<c__DisplayClass4_0.g__BuildServiceProvider|3() at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_0.b__2(Int64 k) at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.GetOrAdd(IDbContextOptions options, >Boolean providerRequired) at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity entity) at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState >entityState) at Microsoft.EntityFrameworkCore.DbContext.Add[TEntity](TEntity entity) at contatinApi.Data.SeedData.SeedUsers() in D:\dev\contatinapi\Data\SeedData.cs:line 24 at System.Threading.Tasks.Task.<>c.b__139_1(Object state) at System.Threading.QueueUserWorkItemCallback.<>c.<.cctor>b__6_0(QueueUserWorkItemCallback quwi) at System.Threading.ExecutionContext.RunForThreadPoolUnsafe[TState](ExecutionContext >executionContext, Action`1 callback, TState& state) at System.Threading.QueueUserWorkItemCallback.Execute() at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

The User class:

public class User
    {
        public int Id{get;set;}
        public string LoginEmail{get;set;}
        public string UserName{get;set;}
        public DateTime CreatedAt{get;set;}
        public List<Contact> Contacts {get;set;}
        public List<ContactList> ContactLists{get;set;}
    }

Both the EF Core and MySQL packages are updated. Also, i tried using stored procedures and it gave the same results.

The content of Ex was:

The value of Ex was {System.TypeLoadException: Method 'Create' in type 'MySql.Data.EntityFrameworkCore.Query.Internal.MySQLSqlTranslatingExpressionVisitorFactory' from assembly 'MySql.Data.EntityFrameworkCore, Version=8.0.22.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' does not have an implementation. at MySql.Data.EntityFrameworkCore.Extensions.MySQLServiceCollectionExtensions.AddEntityFrameworkMySQL(IServiceCollection services) at MySql.Data.EntityFrameworkCore.Infrastructure.Internal.MySQLOptionsExtension.ApplyServices(IServiceCollection services) at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.ApplyServices(IDbContextOptions options, ServiceCollection services) at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_0.g__BuildServiceProvider|3() at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_0.b__2(Int64 k) at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.GetOrAdd(IDbContextOptions options, Boolean providerRequired) at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies.get_StateManager() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.EntryWithoutDetectChanges(TEntity entity) at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.Add(TEntity entity) at contatinApi.Data.SeedData.SeedUsers() in D:\dev\ContatinApi\Data\SeedData.cs:line 40}

5 Answers

If you're using Microsoft.EntityFrameworkCore 5.0 downgrade it to Microsoft.EntityFrameworkCore 3.1.10 MySQL EF 8.0.22 is currently not compatiable with Microsoft.EntityFrameworkCore 5.0

I have a working Code until I upgraded to Microsoft.EntityFrameworkCore 5.0 then I got same error, Downgraded and it worked!

Hoping to post a Bug report on MySQL Bug Forum

I have resolved this issue following this:-

  1. upgrade Microsoft.EntityFrameworkCore to version 5.0.1

  2. upgrade Pomelo.EntityFrameworkCore.MySql to version 5.0.0-alpha.2

  3. add the code blocks into ConfigureServices method of Startup.cs file

    var connectionString = _configuration.GetConnectionString("userDB"); services.AddDbContext(options =>
    options.UseMySql(connectionString,new MySqlServerVersion(new Version(10, 1, 40)), mySqlOptions => mySqlOptions .CharSetBehavior(CharSetBehavior.NeverAppend)));

To get mysql server version run the query to any of mysql server editor like MySql Workbench or HeidiSQL

SELECT VERSION()

While following an EF Core tutorial for MySql using Migrations and getting the error "Method 'Create' does not have an implementation" and lots of Googling, I Downgraded my csproj file from net5.0 to netcoreapp3.1:

<TargetFramework>netcoreapp3.1</TargetFramework>

And included the following Nuget packages using terminal dotnet commands inside the project directory:

dotnet add package Pomelo.EntityFrameworkCore.MySql --version 5.0.0-alpha.2
...

dotnet list package                    
    Project 'XYZ' has the following package references
       [netcoreapp3.1]: 
       Top-level Package                           Requested       Resolved     
       > Microsoft.EntityFrameworkCore             5.0.1           5.0.1        
       > Microsoft.EntityFrameworkCore.Design      5.0.1           5.0.1        
       > Microsoft.EntityFrameworkCore.Tools       5.0.1           5.0.1        
       > Pomelo.EntityFrameworkCore.MySql          5.0.0-alpha.2   5.0.0-alpha.2

As example, one of the model files is Student.cs:

namespace EFCoreTutorial.Model
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
    }
}

I created the db context file SchoolContext.cs with my personal connection string as:

using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;

namespace EFCoreTutorial.Data
{
  public class SchoolContext : DbContext
  {
    public DbSet<Model.Student> Students { get; set; }
    public DbSet<Model.Course> Courses { get; set; }
        
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      string connectionString = "server=localhost;port=3306;database=SchoolDB;user=root;password=******";
      optionsBuilder.UseMySql(connectionString, new MySqlServerVersion(new System.Version(8, 0, 22)), mySqlOptions => mySqlOptions.CharSetBehavior(CharSetBehavior.NeverAppend));
    }
  }
}

then you can create the database and the empty tables defined in the Model with

dotnet ef migrations add CreateSchoolDB <- just a label 
dotnet ef migrations list   <- to verify it is pending
dotnet ef database update   <- the database will be created/updated
dotnet ef migrations list   <- to verify

finally verify in mysql:

mysql> show databases;
mysql> use SchoolDB;
mysql> show tables;

Succes! The Database and tables were completely created from the models and DB Context definition.

Try:

  _context.Users.Add(new User{LoginEmail=email, CreatedAt=DateTime.Now });  
        await _context.SaveChangesAsync();  

or better 
try
{
var newUser= new User{LoginEmail=email, CreatedAt=DateTime.Now };
  _context.Users.Add(newUser);  
await _context.SaveChangesAsync();  
}
catch (Exception ex)
{
var errorMessage = ex.Message;
        
}
in this case you can get a new key if you need;

UPDATE:

instead of    _context.Users.Add(newUser);  

Try:

_context.Entry(newUser).State = EntityState.Added;

But why your ID of your User class doesn't have attribute [Key] and CreateDate doesn't have attribut [Column(TypeName = "datetime")] ?. What kind of validations do you have? Can you post some of _context that is relevant to User?

Install the following nuget package for MySql driver from Pomelo.EntityFrameworkCore.MySql

Other Nuget packages will be:

<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.10">
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
  <PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.22" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="5.0.1" />

Run the following command to get the version of your MySql

SELECT VERSION()

In Startup.cs add the following namespaces:

using System;
using IdentityWithEFPlayground.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Pomelo.EntityFrameworkCore.MySql;

In ConfigureServices method of Startup.cs add the following code:

        var serverVersion = new MySqlServerVersion(new Version(8, 0, 26)); // Get the value from SELECT VERSION()
        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        services.AddDbContext<AppDBContext>(c => c.UseMySql(connectionString, serverVersion));
        services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<AppDBContext>();

In ther Terminal run the following command to update/create the database via EF Migrations:

dotnet ef migrations add IdentityUser
dotnet ef database update  

You will see the ASP.NET Identity tables in your database:

enter image description here

Related