Home > Software engineering >  My database context reference is always returning null, how can this be fixed?
My database context reference is always returning null, how can this be fixed?

Time:09-23

I have an issue where my database context is null.

I need to call this method in my startup.cs class like this:

MorningOrders meds = new MorningOrders();

meds.CompleteOrders();

And here is my class:

public class MorningOrders
{
    private readonly EbContext _context;

    public MorningOrders()
    { }

    public MorningOrders(EbContext context)
    {
        _context = context;
    }

    public bool CompleteOrders()
    { 
     // process orders
    }
}

Everytime I run it though, I get an error saying _context is null

Is there a way to fix this?

thanks!

CodePudding user response:

Remove the parameterless constructor from your class:

public MorningOrders()
{ }

...and always inject it with a context:

using (var context = new EbContext())
{
    MorningOrders meds = new MorningOrders(context);

    meds.CompleteOrders();
}
  • Related