Unable to create an object of type 'DbContext'. For the different patterns supported at design time 电脑版发表于:2022/5/5 12:27 如果在做EFCore migration时碰到如下错误:Unable to create an object of type 'DbContext'. For the different patterns supported at design time **可尝试以下步骤进行处理:** 1:检查是否未实现EFContext默认构造函数 2:尝试清理解决方案,清除目录下的bin和obj 3:如果还不行,尝试在DbContext同级目录下添加类DesignTimeDbContextFactory 也就是自己写点逻辑执行以下执行迁移命令的逻辑 ``` /* This class is needed for EF Core console commands * (like Add-Migration and Update-Database commands) */ public class WyJBLandDbContextFactory : IDesignTimeDbContextFactory<WyJBLandDbContext> { public WyJBLandDbContext CreateDbContext(string[] args) { //BookStoreEfCoreEntityExtensionMappings.Configure(); var configuration = BuildConfiguration(); string conn = configuration.GetConnectionString("conn_mysql"); AddTestLog(conn); var builder = new DbContextOptionsBuilder<WyJBLandDbContext>() .UseMySql(conn,ServerVersion.AutoDetect(conn)); return new WyJBLandDbContext(builder.Options); } /// <summary> /// 记录一点内容用于测试 /// </summary> /// <param name="content"></param> public void AddTestLog(string content) { using (FileStream filestraem = new FileStream("d:/log.txt", FileMode.Append)) { using (StreamWriter write = new StreamWriter(filestraem)) { write.WriteLine(content); write.WriteLine("记录时间:" + DateTime.Now.ToString()); write.WriteLine("----------------------------------------"); write.Flush(); } } } private static IConfigurationRoot BuildConfiguration() { var builder = new ConfigurationBuilder() .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../WY.JBLand.API/")) .AddJsonFile("appsettings.json", optional: true); return builder.Build(); } } ```