You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET7下EF Core+MySQL执行数据库更新时缺失方法异常排查

执行dotnet ef database update时出现MissingMethodException错误

已安装的NuGet包

  • Microsoft.EntityFrameworkCore 7.0.0
  • Microsoft.EntityFrameworkCore.Design 7.0.0
  • MySql.EntityFrameworkCore 7.0.0-preview5+MySQL8.0.31

上下文类代码

namespace API.Context
{
    public class EventContext : DbContext
    {
        public EventContext(DbContextOptions<EventContext> options) : base(options)
        {
        }

        public DbSet<Property> Property { get; set; }

        public DbSet<Event> Event { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Event>(entity =>
            {
                entity.HasKey(e => e.ID);
                entity.Property(e => e.Title).IsRequired();
            });

            modelBuilder.Entity<Property>(entity =>
            {
                entity.HasKey(e => e.ID);
                entity.Property(e => e.Key).IsRequired();
                entity.Property(e => e.Value).IsRequired();
                entity.HasOne(d => d.Event)
            .WithMany(p => p.Properties);
            });
        }
    }
}

Program.cs代码

using API.Context;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<EventContext>(x => x.UseMySQL(builder.Configuration.GetConnectionString("DefaultConnection")));

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

错误信息

System.MissingMethodException: Method not found: 'System.Collections.Generic.IList`1<Microsoft.EntityFrameworkCore.Metadata.Conventions.IModelInitializedConvention> Microsoft.EntityFrameworkCore.Metadata.Conventions.ConventionSet.get_ModelInitializedConventions()'.

问题

请问我遗漏了什么配置或步骤?


解决方案

这个错误的核心原因是MySQL EF Core驱动的预览版本与正式版EF Core 7.0.0存在版本兼容性冲突。MySql.EntityFrameworkCore 7.0.0-preview5是预览版本,其内部依赖的EF Core API与你使用的正式版Microsoft.EntityFrameworkCore 7.0.0不匹配,导致找不到指定方法。

具体解决步骤:

  1. 卸载当前的MySql.EntityFrameworkCore预览包
  2. 安装与EF Core 7.0.0版本完全匹配的正式版MySQL EF Core驱动,确保驱动版本和Microsoft.EntityFrameworkCore、Microsoft.EntityFrameworkCore.Design的版本保持一致(均为7.0.0)。

额外检查项:

  • 清理NuGet缓存避免版本残留:执行命令 dotnet nuget locals all --clear
  • 重新构建项目后,再执行dotnet ef database update

内容的提问来源于stack exchange,提问作者Neigaard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:01:13