在ASP.NET核心中使用时,如何从另一个项目访问EF核心的DbContext?

时间:2018-06-11 19:59:57

标签: c# entity-framework asp.net-core dependency-injection entity-framework-core

我按照模式使用EF Core和ASP.NET核心,一切都很顺利。但最近我创建了一个“计算”项目,并希望从中进行数据库调用。

问题是我不知道如何创建新的DbContextOptions。在我用

完成的代码中
   services.AddDbContext<RetContext>(options => options
            .UseLazyLoadingProxies()
            .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

但是在新的.NET核心类中,我需要手动提供它。我该怎么做呢 ?我的代码是这样的:

 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 个答案:

答案 0 :(得分:1)

您可以像这样实例化DbContext

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);