Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Problem with init dbContext : No database provider has been configured for this DbContext.

$
0
0

Hi

In my project, i've setup my db context, now when i want to work with database, i've got this error :

System.InvalidOperationException: 'No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.'

Here is my startup class for configure service method :

...
public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }        

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<Models.MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDbContextConnectionString")));
        }
...

And here is my appsettings file :

{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
    }
  },"AllowedHosts": "*","ConnectionStrings": {"MyDbContextConnectionString": "Data Source=.;Initial Catalog=MyDb;Integrated Security=True;MultipleActiveResultSets=true"
  }
}

And here is my action method :

public class PatientController : Controller
    {
        private MyDbContext _dbContext = new MyDbContext();

	...

        public IActionResult SearchPatient(string q)
        {
            var patients = _dbContext.Patients.Where(p => p.NationalID == q || p.PatientCaseID == q).ToList(); // Cause error!!
            return PartialView("_PatientsSearchResult", patients);
        }
    }

Where is my problem & how to solve it?

Thanks in Advance


Viewing all articles
Browse latest Browse all 9386

Trending Articles