I am trying to inject a simple connection string in an ASP.NET Core 2.1 API project.
appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=xxx.database.windows.net;Database=xxx;User Id=frontend;Password=xxx;"
}
}
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
var connStr = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<DB>(options => options.UseSqlServer(connStr));
DbContext:
public class DB : DbContext
{
public DB(DbContextOptions<DbContext> options) : base(options) { }
public DB() { }
public DbSet<MenuItem> MenuItemList { get; set; }
}
My Controller:
public class MenuItemsController : ControllerBase
{
DB _context;
public MenuItemsController(DB context)
{
_context = context;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
try
{
var ddd = _context.MenuItemList.ToList();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return new string[] { "value1", "value2" };
}
}
I get following error:
No database provider has been configured for this DbContext.
The connection string is read correctly from the appsettings file, am I missing something? I have read other posts where people just configure the connection part in the DB context but I would prefer to do it this way with injection.