Search code examples
entity-frameworkasp.net-corerazor-pages

How to reference DbContext in a class file .NET 6 EF


UPDATE: Add DI to the top. @inject ApplicationDbContext db

Outside of razor pages.. I have a utility class and need to query the db from EF to get a value to populate in a razor partial.

In the _MenuPartial need to construct a class and get value.

@{
     WebMessageManagement wm = new WebMessageManagement(???dbcontext???);
     wm.GetMessageCount(); //returns int
 }

_MenuPartial code snippet: enter image description here

In the WebMessageManagement class I have this:

  public class WebMessageManagement  
    {    
        ApplicationDbContext _db;
      
        public WebMessageManagement(ApplicationDbContext db)
        {
            _db = db; 
        }
        public int GetMessageCount()
        {
            var count = (from o in _db.WebMessages
                         where o.Id >= 3109
                         from t in o.Email
                         select t).Count();
            return count;
        }
    }

Normal razor pages seem to have the ApplicationDbContext injected. But I am creating a class outside razor pages. Do I need to set this context up again for non razor?


Solution

  • Injection puts the object into the webrequest to the controller (99% of the time unless you are doing something very fancy). In this case you can just pass the context as a variable to the class function.

    WebMessageManagement wm = new WebMessageManagement();
    wm.GetMessageCount(dbcontext); //returns int
    

    and then in the class file

    public class WebMessageManagement  
    {    
      
        public WebMessageManagement()
        {
            
        }
        public int GetMessageCount(ApplicationDbContext db)
        {
            var count = (from o in db.WebMessages
                         where o.Id >= 3109
                         from t in o.Email
                         select t).Count();
            return count;
        }
    }
    

    I think this will give you what you needed.