System.TypeLoadException:方法“Create”在类型“MySql.Data.EntityFrameworkCore.Query.Internal.MySQLSqlTranslatingExpressionVisitorFactory”中

vatpfxk5  于 2023-08-02  发布在  Mysql
关注(0)|答案(6)|浏览(171)

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

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(IServ> iceCollection services)在MySql. Data. EntityFrameworkCore. Infrastructure. Internal. MySQLOptionsExtension. ApplyServices(IServiceColle> ction services)在Microsoft. EntityFrameworkCore. Internal. ServiceProviderCache. ApplyServices(IDbContextOptions> options,ServiceCollection services)在Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<c__DisplayClass4_0.g__BuildServiceProvider| Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache中的3()。<> c__DisplayClass4_0.b__2(Int64 k)at System.收藏。并发症。ConcurrentDictionary 2.GetOrAdd(TKey key, Func 2 valueFactory)。EntityFrameworkCore.内部。ServiceProviderCache。GetOrAdd(IDbContextOptions选项,> Boolean providerRequired)在Microsoft。EntityFrameworkCore. DbContext。Microsoft的get_InternalServiceProvider()。EntityFrameworkCore. DbContext。Microsoft的get_DbContextDependencies()。EntityFrameworkCore. DbContext。Microsoft的EntryWithoutDetectChanges [TEntity](TEntity实体)。EntityFrameworkCore. DbContext。Microsoft的SetEntityState [TEntity](TEntity entity,EntityState> entityState)。EntityFrameworkCore. DbContext。在contatinApi处添加[TEntity](TEntity实体)。数据。种子数据SeedUsers()in D:\dev\contatinapi\Data\SeedData。cs:System.Threading.Tasks.Task中的第24行。<> c.b__139_1(对象状态),位于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()
User类:

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:程序集“MySql. Data. EntityFrameworkCore,Version = 8.0.22.0,Culture = neutral,PublicKeyToken = c5687fc88969c44d”中的类型“MySql. Data. EntityFrameworkCore. Query. Internal. MySQLSqlTranslatingExpressionVisitorFactory”中的方法“Create”没有实现。位于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| Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache中的3()。<>系统上的c__DisplayClass4_0.b__2(Int64 k)。收藏。同时发生。ConcurrentDiction2.GetOrAdd(TKey key, Func 2 valueFactory)。EntityFrameworkCore。内在的。ServiceProviderCache。GetOrAdd(IDbContextOptions选项,Boolean providerRequired)。EntityFrameworkCore. DbContext。Microsoft的get_InternalServiceProvider()。EntityFrameworkCore. DbContext。Microsoft的get_DbContextDependencies()。EntityFrameworkCore. DbContext。微软。EntityFrameworkCore.内部。IDbContextDependencies。get_StateManager()在Microsoft。EntityFrameworkCore.内部。InternalDbSet 1.EntryWithoutDetectChanges(TEntity entity) at Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.Add(TEntity entity)at contatinApi.数据。种子数据SeedUsers()in D:\dev\ContatinApi\Data\SeedData。cs:第40行}

vmpqdwk3

vmpqdwk31#

如果您使用的是Microsoft.EntityFrameworkCore 5.0,请将其降级为Microsoft.EntityFrameworkCore 3.1.10 MySQL EF 8.0.22当前与Microsoft.EntityFrameworkCore 5.0不兼容
我有一个工作代码,直到我升级到微软。EntityFrameworkCore 5. 0然后我得到了同样的错误,降级,它的工作!
希望在MySQL Bug论坛上发布Bug报告

cetgtptt

cetgtptt2#

我已经解决了这个问题如下:-
1.将Microsoft.EntityFrameworkCore升级到版本5.0.1
1.将Pomelo.EntityFrameworkCore.MySql升级到版本5.0.0-alpha.2
1.将代码块添加到Startup.cs文件的ConfigureServices方法中
var connectionString = _configuration.GetConnectionString(“userDB”); services.AddDbContext(options =>
使用MySql(connectionString,new MySqlServerVersion(new Version(10,1,40)),mySqlOptions => mySqlOptions .CharSetBehavior(CharSetBehavior.NeverAppend));
要获取mysql服务器版本,请运行查询到任何mysql服务器编辑器,如MySql Workbench或HeidiSQL

SELECT VERSION()

字符串

zf2sa74q

zf2sa74q3#

在使用Migrations进行MySql的EF Core教程并获得错误“Method 'Create' does not have an implementation”和大量Google搜索时,我将我的csproj文件从net5.0降级到netcoreapp3.1:

<TargetFramework>netcoreapp3.1</TargetFramework>

字符串
并在项目目录中使用terminaldotnet命令包含以下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上下文定义中创建。

hc8w905p

hc8w905p4#

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标识表:
x1c 0d1x的数据

23c0lvtd

23c0lvtd5#

这个解决方案对我很有效:如果您使用MySql database连接,则使用依赖项MySql.EntityFrameworkCore而不是MySql.Data.EntityFrameworkCore

jxct1oxe

jxct1oxe6#

试试看:

_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吗?

相关问题