2

I have an issue that requires me create a new Core Console application in the same project as my Core 2.0 MVC Web Application. In my MVC application I can easily connect to my database via the system data context. However when I try to connect using the same code in my console application, the query will return that the db is null. I have referenced my MVC project in the console application but no luck. Thanks in advance. Please see below:

Data Context

public class SystemDataContext : DbContext
{
    public SystemDataContext(DbContextOptions<SystemDataContext> options)
        : base(options)
    { }

    public DbSet<Facility> Facility { get; set; }
}

MVC - Works

public class FacilityService
{
    private SystemDataContext db;
    public FacilityService(SystemDataContext dataBase)
    {
        db = dataBase;
    }

    public List<Facility> GetFacilities()
    {
        var facilities = db.Facility.ToList();
        return facilities;
    }
}

Console Application - Returns db null error

public class Program
{
    private SystemDataContext db;
    public Program(SystemDataContext dataBase)
    {
        db = dataBase;
    }

    public static void Main(string[] args)
    {

        var facilities = db.Facility.ToList();

        Console.WriteLine("Hello World!");
    }
}
Antoin McCloskey
  • 121
  • 1
  • 2
  • 9

1 Answers1

4

That's because MVC Core is configuring the dependency injection properly, as opposite to the console application.

In your console application, you may instantiate your DbContext manually using this:

var builder = new ConfigurationBuilder()
              .SetBasePath(Directory.GetCurrentDirectory())
              .AddJsonFile("appsettings.json");

var configuration = builder.Build();
var optionsBuilder = new DbContextOptionsBuilder<SystemDataContext>();
optionsBuilder.UseSqlServer(configuration.GetConnection("DefaultConnection"));
var db = new SystemDataContext(optionsBuilder.Options);

You should have the appsettings.json with the connection strings properly in your console application as well.

It would be also a good idea to put your DbContext in a class library project, and reference it from both the MVC and Console apps.

Alisson Reinaldo Silva
  • 10,009
  • 5
  • 65
  • 83