Visual Studio 尝试激活DbContext时,无法解析类型Microsoft的服务,

wn9m85ua  于 2023-11-21  发布在  其他
关注(0)|答案(4)|浏览(195)

当我尝试用视图和实体框架搭建一个MVC控制器时,如下所示:


的数据
我得到这个错误:



这是我的DbContext类:

  1. namespace Infrastructure
  2. {
  3. public class DataContext : DbContext
  4. {
  5. public DataContext(DbContextOptions<DataContext> options) : base(options)
  6. {
  7. }
  8. public DbSet<Owner> owners { get; set; }
  9. public DbSet<ProtoFile> protoFiles { get; set; }
  10. protected override void OnModelCreating(ModelBuilder modelBuilder)
  11. {
  12. base.OnModelCreating(modelBuilder);
  13. modelBuilder.Entity<Owner>().Property(x => x.Id).HasDefaultValueSql("NEWID()");
  14. modelBuilder.Entity<ProtoFile>().Property(x => x.Id).HasDefaultValueSql("NEWID()");
  15. modelBuilder.Entity<Owner>().HasData(
  16. new Owner
  17. {
  18. Id = Guid.NewGuid(),
  19. Avatar = "avatar.jpg",
  20. FullName = "Mohammad AlMohammad AlMahmoud",
  21. Profile = ".NET Full Stack Developer"
  22. });
  23. }
  24. }
  25. }

字符串

tyky79it

tyky79it1#

我最终通过添加IDesignTimeDbContextFactory修复了它

  1. public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
  2. {
  3. public BloggingContext CreateDbContext(string[] args)
  4. {
  5. var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
  6. optionsBuilder.UseSqlite("Data Source=blog.db");
  7. return new BloggingContext(optionsBuilder.Options);
  8. }
  9. }

字符串

gcuhipw9

gcuhipw92#

我通过将此代码添加到DataContext类来解决此问题

  1. protected override void OnConfiguring(DbContextOptionsBuilder DataContext)
  2. {
  3. optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test");
  4. }

字符串
它被解决了,但生成代码后,我有一些问题,当我运行应用程序,所以我删除它和应用程序成功工作
来自Microsoft文档https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/

b4qexyjb

b4qexyjb3#

你必须把这段代码添加到你的程序类中(如果你使用net 6)

  1. builder.Services.AddDbContext<DataContext>(options =>
  2. options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

字符串
或者如果你使用的是net 5或更低版本,将其添加到启动类中。

  1. services.AddDbContext<DataContext>(.....


并删除

  1. base.OnModelCreating(modelBuilder);

展开查看全部
falq053o

falq053o4#

这里也有同样的问题。发现我需要将上下文类作为服务添加到Program.cs中的构建器中。在我的情况下,我使用InMemoryDatabase选项

  1. builder.Services.AddDbContext<WebshopContext>(opt =>
  2. opt.UseInMemoryDatabase("AccountRequestList"));

字符串

相关问题