Access to DBContext within _ViewStart.cshtml

Viewed 944

I want some code to execute on every page of my ASP .Net Core site. It's primarily setting session variables. I figured the best place to put it would be in _ViewStart.cshtml, but I don't have access to my dbcontext there. So my question is two-fold -- first, am I doing the wrong thing, is there a better place to put this code so that it executes on every page of the site? Second, how do I inject my dbcontext into _ViewStart.cshtml so I can do some database queries in the code there?

1 Answers

Here is a working demo like below:

1.Be sure your have imported the namespace of your DbContext in _ViewImports.cshtml like below:

@using YourProjectName.Data

2.Configure your _ViewStart.cshtml like below:

@inject MyDbContext _context;
@{
    Layout = "_Layout";
    ViewBag.Context = _context;
}

3.Get the data in any razor view:

@{
    ViewData["Title"] = "Home Page";
    var data = ViewBag.Context as MyDbContext;
}

@data.Test.Select(u=>u.Name).FirstOrDefault()

4.My testing model:

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
}

5.My testing DbContext:

namespace Mvc3_0.Data
{
    public class MyDbContext : DbContext
    {
        public MyDbContext (DbContextOptions<MyDbContext> options)
            : base(options)
        {
        }

        public DbSet<Test> Test { get; set; }
    }
}
Related