系统类型加载异常:在类型“MySql.Data.EntityFrameworkCore.Query.Internal.MySQLSqlTranslatingExpressionVisitorFactory”中的方法“Create”

17

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

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”方法,来自程序集“MySql.Data.EntityFrameworkCore, Version=8.0.22.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d”的实现不存在。 在MySql.Data.EntityFrameworkCore.Extensions.MySQLServiceCollectionExtensions.AddEntityFrameworkMySQL(IServiceCollection services)中 在MySql.Data.EntityFrameworkCore.Infrastructure.Internal.MySQLOptionsExtension.ApplyServices(IServiceCollection services)中 在Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.ApplyServices(IDbContextOptions options, ServiceCollection services)中 在Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_0.b__2(Int64 k) 在System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) 在Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.GetOrAdd(IDbContextOptions options, Boolean providerRequired) 在Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() 在Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() 在Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity entity) 在Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState) 在Microsoft.EntityFrameworkCore.DbContext.Add[TEntity](TEntity entity) 在contatinApi.Data.SeedData.SeedUsers() 位置 D:\dev\contatinapi\Data\SeedData.cs:行号 24 在System.Threading.Tasks.Task.<>c.b__139_1(Object state) 在System.Threading.QueueUserWorkItemCallback.<>c.<.cctor>b__6_0(QueueUserWorkItemCallback quwi) 在System.Threading.ExecutionContext.RunForThreadPoolUnsafe[TState](ExecutionContext executionContext, Action`1 callback, TState& state) 在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' does not have an implementation. 在 MySql.Data.EntityFrameworkCore.Extensions.MySQLServiceCollectionExtensions.AddEntityFrameworkMySQL(IServiceCollection services) 中 在 MySql.Data.EntityFrameworkCore.Infrastructure.Internal.MySQLOptionsExtension.ApplyServices(IServiceCollection services) 中 在 Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.ApplyServices(IDbContextOptions options, ServiceCollection services) 中 在 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 options, Boolean 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) 中 在 Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.Add(TEntity entity) 中 在 contatinApi.Data.SeedData.SeedUsers() 中,位于 D:\dev\ContatinApi\Data\SeedData.cs:line 40}


1
你好,我遇到了完全相同的问题,你解决了吗? - Brandon Miller
6个回答

25

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

我有一个正常工作的代码,直到我升级到 Microsoft.EntityFrameworkCore 5.0 ,然后遇到了同样的错误,我降级后它就可以运行了!

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


6
如果您想尝试,Pomelo MySQL提供程序已经支持EF Core 5.0的预发布版本。 - Mark G
@MarkG 我正在使用Pomelo.EntityFrameworkCore.MySql 5.0.0-alpha.2版本构建。同样的问题仍然存在。 - Snipe3000
3
如果您的项目文件中仍然引用了 MySql.Data.EntityFrameworkCore,请确保使用 UseMySql() 而不是 UseMySQL()。请注意保持原文意思不变,使语言更加通俗易懂。 - Mark G

3

我已经解决了这个问题,按照以下步骤进行:

  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 =>
    options.UseMySql(connectionString,new MySqlServerVersion(new Version(10, 1, 40)), mySqlOptions => mySqlOptions .CharSetBehavior(CharSetBehavior.NeverAppend)));

要获取 MySQL 服务器版本,请在任何 MySQL 服务器编辑器(如 MySql Workbench 或 HeidiSQL)中运行查询。

SELECT VERSION()

2

在使用迁移时,按照使用EF Core教程操作MySql时,出现了错误“方法'Create'没有实现”,并且进行了大量的搜索后,我将我的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;

成功!数据库和表已完全根据模型和DB Context定义创建。


1

请安装来自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身份验证表:

enter image description here


1
这个解决方案对我有效: 如果你正在连接到 MySql 数据库,那么请使用依赖项 MySql.EntityFrameworkCore,而不是 MySql.Data.EntityFrameworkCore。

你的回答可以通过提供更多支持性信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人能够确认你的回答是否正确。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community
这是最好的答案!!!像魔法一样有效。其他的回答都太差劲了。只需要做这些就可以了。非常感谢你! - Dean Friedland

0

尝试:

  _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")]属性呢?你有哪些验证方式?你能发布一些与User相关的上下文吗?

“直接添加到数据库中”是什么意思?而且,你是否将“_context.Add(newUser)”更改为“_context.Users.Add(newUser)”? - Serge
这些默认值非常棘手。为了触发默认值,您必须发布 null 值。DateTime 默认具有非常奇怪的日期,因此您必须将类属性更改为 DateTime?或在添加之前分配实际值。 - Serge
我不这么认为。我已经使用Add()函数上千次了,它总是有效的。你尝试过获取用户吗?也许是_context出了问题? - Serge
更新了问题,例如值完全相同的错误。 - Pedro Lucas Maia Ramos
我注意到你的User类没有任何属性?你能发布一下你的DB上下文中USER部分的代码吗? - Serge
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接