tnblog
首页
视频
资源
登录
什么时候才能领悟,取之越多失之越多
排名
5
文章
229
粉丝
15
评论
7
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

Unable to create an object of type 'DbContext'. For the different patterns supported at design time

9069人阅读 2022/5/5 12:27 总访问:1165765 评论:0 收藏:0 手机
分类: .net core

如果在做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
也就是自己写点逻辑执行以下执行迁移命令的逻辑

  1. /* This class is needed for EF Core console commands
  2. * (like Add-Migration and Update-Database commands) */
  3. public class WyJBLandDbContextFactory : IDesignTimeDbContextFactory<WyJBLandDbContext>
  4. {
  5. public WyJBLandDbContext CreateDbContext(string[] args)
  6. {
  7. //BookStoreEfCoreEntityExtensionMappings.Configure();
  8. var configuration = BuildConfiguration();
  9. string conn = configuration.GetConnectionString("conn_mysql");
  10. AddTestLog(conn);
  11. var builder = new DbContextOptionsBuilder<WyJBLandDbContext>()
  12. .UseMySql(conn,ServerVersion.AutoDetect(conn));
  13. return new WyJBLandDbContext(builder.Options);
  14. }
  15. /// <summary>
  16. /// 记录一点内容用于测试
  17. /// </summary>
  18. /// <param name="content"></param>
  19. public void AddTestLog(string content)
  20. {
  21. using (FileStream filestraem = new FileStream("d:/log.txt", FileMode.Append))
  22. {
  23. using (StreamWriter write = new StreamWriter(filestraem))
  24. {
  25. write.WriteLine(content);
  26. write.WriteLine("记录时间:" + DateTime.Now.ToString());
  27. write.WriteLine("----------------------------------------");
  28. write.Flush();
  29. }
  30. }
  31. }
  32. private static IConfigurationRoot BuildConfiguration()
  33. {
  34. var builder = new ConfigurationBuilder()
  35. .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../WY.JBLand.API/"))
  36. .AddJsonFile("appsettings.json", optional: true);
  37. return builder.Build();
  38. }
  39. }

欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)

评价
悲痛藏于心,欢喜言于表。说的不就是我们吗!