How to I access the DbContext of EF core from another project when used in ASP.NET core?

时光毁灭记忆、已成空白 提交于 2020-03-02 12:27:12

问题


I followed the pattern to use EF Core with ASP.NET core and all is well. But recently I created a 'Calculation' project and want to make database calls from it.

The problem is I don't know how to create a new DbContextOptions. In my code that is done with

   services.AddDbContext<RetContext>(options => options
            .UseLazyLoadingProxies()
            .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

But in a new .NET core class I need to provide it manually. How do I do this ? My code is like this:

 public static class LoadData
{
    public static IConfiguration Configuration { get; }

    public static RefProgramProfileData Load_RefProgramProfileData(string code)
    {
        // var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
        // optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));

        //How do I make an optionsbuilder and get the configuration from the WEB project?
       UnitOfWork uow = new UnitOfWork(new RetContext(optionsBuilder));


        var loadedRefProgramProfileData  = uow.RefProgramProfileDataRepository
            .Find(x => x.ProgramCode == code).FirstOrDefault();

        return loadedRefProgramProfileData;
    }
}

回答1:


You may instantiate your DbContext like this:

var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
var configuration = builder.Build();
var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
optionsBuilder.UseSqlServer(configuration.GetConnection("DefaultConnection"));
_context = new RetContext(optionsBuilder.Options); 

However, the ideal is to use dependency injection. Let's say you have a class CalculationService in your other project. For that, you need to register that class as a service that can be injected:

services.AddScoped<CalculationService>();

Then your class can receive DbContext (or any other services) through DI:

public class CalculationService
{
    private RetContext _context;

    public CalculationService(RetContext context)
    {
        _context = context;
    }
}

Naturally, you won't be able to instantiate your class manually like this:

var service = new CalculationService();

Instead, you'd need to make whatever class needs to use your CalculationService to also receive it through DI and make that class injectable as well.



来源:https://stackoverflow.com/questions/50805184/how-to-i-access-the-dbcontext-of-ef-core-from-another-project-when-used-in-asp-n

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