I have an asp.net core 2 webapplication with EF 6. The way I have been using db context so far is using dependency injection provided by asp.net core to inject the context into controllers:
protected DbContext dbContext;
public BaseController(DbContext context)
{
dbContext = context;
}
In many of my razor views, I call an extension method to initialize a telerik grid, passing it options. So far I have not needed to access the db context, but now I need to access it in the extension method for some logic:
public static GridBuilder<T> BaseProcessGrid<T>(this GridBuilder<T> helper, string controllerName, string gridName)
where T : class, IProcessViewModel
{
bool showDelete = false;
//check if the current user has edit rights
using (var db = new DbContext())
{
var users = db.Users.ToList(); // <--- this just doesn't get any records.
}
When trying to instantiate a new db context from within the static method, it just doesn't fetch any records. I need to figure out how to actually access a new instance of the DbContext, or somehow access the scoped service defined in my Startup.cs:
services.AddScoped(_ => new MantleMapperContext(Configuration.GetConnectionString("DbContext")));
EDIT:
As suggested below, I ended up injecting the dbContext service directly into my view and then passing it into the method like so:
@inject DbContext dbContext
OptionModelfor your extension method.