Robel Haile Robel Haile - 1 year ago 202
C# Question

issue with my dbcontext in asp.core. Dont know how to use DbContextOptions object

This is my dbcontext:

public class ShoppingDbContext : IdentityDbContext<User>
{
public ShoppingDbContext(DbContextOptions options) : base(options)
{

}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}

public DbSet<Product> Products { get; set; }

}


earlier today i got an error which i solved by putting in that constructor you see in my code. The one which takes a DbContextOptions as a parameter. But now when i wanna create an instance of this dbcontext i dont know what to put in that parameter:

public static async Task<List<Product>> GetAllProducts()
{
//what should go in here?
ShoppingDbContext db = new ShoppingDbContext(?????????????);
return await db.Products.ToListAsync();
}


if i create an overloading constructor that takes 0 parameters it wont solve the problem cause it would just give me the same error i had before i created the constructor with the DbContextOptions parameter. The error i get if i have a constructor with 0 parameters in dbcontext is this:

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 object in its constructor and passes it to the base constructor for DbContext.

Answer Source

You have to set that inside the Startup.cs as shown below.

public void ConfigureServices(IServiceCollection services)
  {
    var connection = @"Server=(localdb)\mssqllocaldb;Database=MyDb;Trusted_Connection=True;";
    services.AddDbContext<ShoppingDbContext>(options => options.UseSqlServer(connection));
}

After that you have to inject it into your Controller as shown below.

public class MyController : Controller
    {
        private ShoppingDbContext _context;

        public MyController(ShoppingDbContext context)
        {
            _context = context;
        }
}

Then your method is like this :

public static async Task<List<Product>> GetAllProducts()
    {
       return await _context .Products.ToListAsync();
    }