VS2017 Solution to Error Reporting of MVC Controller Added with EF

  • 2021-09-16 06:43:30
  • OfStack

VS2017 Adding EF MVC Controller Error Solution, for your reference, the specific content is as follows

1. Error description: no database provider has been configured fot this DbContext.

This kind of error is caused by the registration of the context. The solution is to override the OnConfiguring method in DBContext to inject the database connection.

In DbContext:


public static string ConnectionString { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
 optionsBuilder.UseSqlServer(ConnectionString);
 base.OnConfiguring(optionsBuilder);
}

In Startup. cs


 public void ConfigureServices(IServiceCollection services)
 {
  // Add framework services.
  var sqlserverConnection = Configuration.GetConnectionString("SQLServerConnection");
  DbContext.ConnectionString = sqlserverConnection;// Pass the configuration connection into DbContext Medium 
  services.AddDbContext<DbContext>(options => options.UseSqlServer(sqlserverConnection));
          
  services.AddMvc();
}

2. Error description: Could not add Model type XXX to DbContext

Error description does not register DbSet attribute. But there is actually public DbSet < XXX > XXX {get; set;} Registered. Will DbSet < XXX > Change the class in to < Namespace + class name > This complete statement can be solved

For more exciting content, you can click "Visual Studio 2017 Development and Use Tutorial", and for the installation tutorial of visual studio, you can click "Visual Studio Installation and Use Manual" to learn. I hope you like it.


Related articles: