Entity Framework Core get context in console application

半城伤御伤魂 提交于 2019-12-24 21:04:35

问题


I have a Visual Studio 2017 solution with 3 projects. One class library that has DAL (.NET Standart 2.0), one AP.NET MVC Application (.NET Core 2.0) and the third Console Application (.NET Framework 4.6.1).

I have referenced DAL in both of the projects. It has implemented Unit of Work pattern and uses Entity Framework Core.

In ASP.NET MVC project I have configured to get context with Dependency Injection as follows

services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"],
        b => {
                b.MigrationsAssembly("OpenData.Backend");
                b.CommandTimeout(4000);
            }
            );
});

Also the Unit of Work is configured as follows

// Repositories
services.AddScoped<IUnitOfWork, HttpUnitOfWork>();

And in the controller I can use it like this:

public class TestServiceController : Controller
{

    private IUnitOfWork _unitOfWork;

    public TestServiceController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }
}

What I want is to do use the same approach in Console application. Since I have not been able to put up the DI in a console application I thought I can create an instance of UnitOfWork

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());

_unitOfWork = new UnitOfWork(new ApplicationDbContext(optionsBuilder.Options));

But I get the following error on the first line of code above

The type 'DAL.ApplicationDbContext' cannot be used as type parameter 'TContext' in the generic type or method 'DbContextOptionsBuilder'. There is no implicit reference conversion from 'DAL.ApplicationDbContext' to 'Microsoft.EntityFrameworkCore.DbContext'.

The second error

The type 'IdentityDbContext<,,>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.AspNetCore.Identity.EntityFrameworkCore, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.

ApplicationDbContext is declared as follows

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
        //Some configuration removed
    }
    // DbSet removed
}

In the ASP.NET Application it is used with ASP.Net Identity, but in the Console Application there is no need of it.

来源:https://stackoverflow.com/questions/53097385/entity-framework-core-get-context-in-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!