【问题标题】:System.TypeLoadException: Method 'Create' in type 'MySql.Data.EntityFrameworkCore.Query.Internal.MySQLSqlTranslatingExpressionVisitorFactory'System.TypeLoadException:“MySql.Data.EntityFrameworkCore.Query.Internal.MySQLSqlTranslatingExpressionVisitorFactory”类型中的方法“创建”
【发布时间】:2021-02-13 06:52:08
【问题描述】:

我正在尝试使用以下代码向数据库添加新用户:

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();  
    }
}

但它一直给我以下错误:

System.TypeLoadException:“MySql.Data.EntityFrameworkCore.Query.Internal.MySQLSqlTranslatingExpressionVisitorFactory”类型中的方法“Create”来自 >assembly 'MySql.Data.EntityFrameworkCore, Version=8.0.22.0, Culture=neutral, >PublicKeyToken=c5687fc88969c44d ' 没有实现。 在 MySql.Data.EntityFrameworkCore.Extensions.MySQLServiceCollectionExtensions.AddEntityFrameworkMySQL(IServ>iceCollection 服务) 在 MySql.Data.EntityFrameworkCore.Infrastructure.Internal.MySQLOptionsExtension.ApplyServices(IServiceColle>ction 服务) 在 Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.ApplyServices(IDbContextOptions >options,ServiceCollection 服务) 在 Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.c__DisplayClass4_0.b__2(Int64 k) 在 System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) 在 Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.GetOrAdd(IDbContextOptions 选项,>Boolean providerRequired) 在 Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() 在 Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() 在 Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity 实体) 在 Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity 实体,EntityState >entityState) 在 Microsoft.EntityFrameworkCore.DbContext.Add[TEntity](TEntity 实体) 在 D:\dev\contatinapi\Data\SeedData.cs:line 24 中的 contatinApi.Data.SeedData.SeedUsers() 在 System.Threading.Tasks.Task.c.b__139_1(对象状态) 在 System.Threading.QueueUserWorkItemCallback.c.<.cctor>b__6_0(QueueUserWorkItemCallback quwi) 在 System.Threading.ExecutionContext.RunForThreadPoolUnsafe[TState](ExecutionContext >executionContext,Action`1 回调,TState& 状态) 在 System.Threading.QueueUserWorkItemCallback.Execute() 在 System.Threading.ThreadPoolWorkQueue.Dispatch() 在 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

用户类:

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;}
    }

EF Core 和 MySQL 包均已更新。另外,我尝试使用存储过程,它给出了相同的结果。

Ex的内容是:

Ex 的值是 {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' 没有实现。 在 MySql.Data.EntityFrameworkCore.Extensions.MySQLServiceCollectionExtensions.AddEntityFrameworkMySQL(IServiceCollection 服务) 在 MySql.Data.EntityFrameworkCore.Infrastructure.Internal.MySQLOptionsExtension.ApplyServices(IServiceCollection 服务) 在 Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.ApplyServices(IDbContextOptions 选项,ServiceCollection 服务) 在 Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.c__DisplayClass4_0.g__BuildServiceProvider|3() 在 Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.c__DisplayClass4_0.b__2(Int64 k) 在 System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) 在 Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.GetOrAdd(IDbContextOptions 选项,布尔 providerRequired) 在 Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() 在 Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() 在 Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies.get_StateManager() 在 Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.EntryWithoutDetectChanges(TEntity entity) at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.Add(TEntity 实体) 在 D:\dev\ContatinApi\Data\SeedData.cs:line 40} 中的 contatinApi.Data.SeedData.SeedUsers() 处}

【问题讨论】:

  • 嗨,我遇到了这个确切的问题,你解决了吗?

标签: c# mysql asp.net-core entity-framework-core


【解决方案1】:

如果您使用的是 Microsoft.EntityFrameworkCore 5.0,请将其降级为 Microsoft.EntityFrameworkCore 3.1.10 MySQL EF 8.0.22 目前与 Microsoft.EntityFrameworkCore 5.0 不兼容

在升级到 Microsoft.EntityFrameworkCore 5.0 之前,我有一个工作代码,然后我得到了同样的错误,降级并且它工作了!

希望在 MySQL 错误论坛上发布错误报告

【讨论】:

  • 如果您想尝试,MySQL 的 Pomelo 提供程序已对 EF Core 5.0 提供预发布支持。
  • @MarkG 我正在使用 Pomelo.EntityFrameworkCore.MySql 5.0.0-alpha.2 构建。同样的问题仍然存在。
  • 如果您的项目文件中仍有对MySql.Data.EntityFrameworkCore 的引用,请确保您使用的是UseMySql() 而不是UseMySQL()
【解决方案2】:

我已经解决了这个问题:-

  1. 将 Microsoft.EntityFrameworkCore 升级到版本 5.0.1

  2. 将 Pomelo.EntityFrameworkCore.MySql 升级到版本 5.0.0-alpha.2

  3. 将代码块添加到 Startup.cs 文件的 ConfigureServices 方法中

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

要获取 mysql 服务器版本,请运行查询到任何 mysql 服务器编辑器,如 MySql Workbench 或 HeidiSQL

SELECT VERSION()

【讨论】:

    【解决方案3】:

    在遵循使用迁移的 MySql 的 EF Core 教程并收到错误“方法'创建'没有实现”和大量谷歌搜索时,我将我的 csproj 文件从 net5.0 降级到 netcoreapp3.1:

    <TargetFramework>netcoreapp3.1</TargetFramework>
    

    并在项目目录中使用终端 dotnet 命令包含以下 Nuget 包:

    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
    

    例如,模型文件之一是 Student.cs:

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

    我使用我的个人连接字符串创建了数据库上下文文件 SchoolContext.cs:

    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));
        }
      }
    }
    

    然后你可以创建数据库和模型中定义的空表

    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
    

    最后在mysql中验证:

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

    成功了!数据库和表完全由模型和数据库上下文定义创建。

    【讨论】:

      【解决方案4】:

      试试:

        _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;
      

      更新:

      instead of    _context.Users.Add(newUser);  
      
      Try:
      
      _context.Entry(newUser).State = EntityState.Added;
      
      

      但是为什么您的 User 类的 ID 没有属性 [Key] 而 CreateDate 没有属性 [Column(TypeName = "datetime")] ?你有什么样的验证?你能发布一些与用户相关的 _context 吗?

      【讨论】:

      • Id 字段(键)设置为直接自动递增到数据库中,用户类中没有必填字段。
      • public DateTime CreatedAt{get;set;} 怎么样。可以为空吗?它应该是公共日期时间? CreatedAt{get;set;} 或者你必须指定日期
      • 它也直接添加到数据库中。我将它们添加到 de 对象中,但仍然出现错误。
      • “它也直接添加到数据库中”是什么意思,您是否将 _context.Add(newUser) 更改为 _context.Users.Add(newUser)?
      • 我更改为 _context.Users.Add 仍然出现错误。在数据库中,createdAt 字段的默认值为 Now()。
      【解决方案5】:

      Pomelo.EntityFrameworkCore.MySql为MySql驱动安装以下nuget包

      其他 Nuget 包将是:

      <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" />
      

      运行以下命令获取你的 MySql 的版本

      SELECT VERSION()
      

      在 Startup.cs 添加以下命名空间:

      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;
      

      在 Startup.cs 的 ConfigureServices 方法中添加以下代码:

              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>();
      

      在终端中运行以下命令以通过 EF 迁移更新/创建数据库:

      dotnet ef migrations add IdentityUser
      dotnet ef database update  
      

      您将在数据库中看到 ASP.NET Identity 表:

      【讨论】:

        猜你喜欢
        • 2019-06-17
        • 1970-01-01
        • 2020-09-28
        • 2016-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多