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

Time:03-24

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?

CodePudding user response:

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.

CodePudding user response:

You need to inject your new class as well. Dependency Injection will figure out how to use your constructor and inject the ApplicationDbContext for you, given that its also registered for dependency injection

services.AddScoped<WebMessageManagement>()

  • Related