Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I add a custom db context in asp.net core 6?

I am following a simple tutorial on connecting databases to a .net core project and I have created a test database and tried to add it into my React js template project. But when I try to add custom db context in program.cs I get an error like this. Here is the code I am using to add db context:

builder.Services.AddDbContext<TransportDBContext>(options => 
            options.UseSqlServer("Server=BURAK\\SQLEXPRESS;Database=TransportDB;uid=sa;pwd=123"));

I have searched for similar problems but most of the time it seemed to create problems with customDbContext parameters being non-generic but in my dbContext it looks like this:

public TransportDBContext(DbContextOptions<TransportDBContext> options)
            : base(options)
        {
        }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The error message you’re seeing is likely related to the fact that the AddDbContext method is not available on the IServiceCollection interface, which is the type of the Services property on the WebHostBuilder class.

One possible solution to this issue is to use the AddDbContext method provided by the Microsoft.Extensions.DependencyInjection namespace in the Startup.cs file of your project.

You would need to add the following namespace:
using Microsoft.Extensions.DependencyInjection;

And then you can use the AddDbContext method in the ConfigureServices method of the Startup class like this:

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseSqlServer("Server=BURAK\SQLEXPRESS;Database=TransportDB;uid=sa;pwd=123"));
}

You also need to make sure that you have the following package installed in your project:

Microsoft.EntityFrameworkCore.SqlServer

Please also check the following things:

Make sure that you have the right version of the packages (Microsoft.AspNetCore.App and Microsoft.EntityFrameworkCore) installed in your project
Make sure that you have the correct connection string.
Make sure that you have the correct version of SQL Server installed.
Make sure that you have installed the correct version of the SQL Server client.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading