【问题标题】:How to I access the DbContext of EF core from another project when used in ASP.NET core?在 ASP.NET 核心中使用时,如何从另一个项目访问 EF 核心的 DbContext?
【发布时间】:2018-11-21 03:27:26
【问题描述】:

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

问题是我不知道如何创建一个新的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;
    }
}

【问题讨论】:

  • 为什么不从计算项目中添加对数据库项目的引用,或者最好还是让它们成为同一个父项目的一部分
  • 我做到了。但不是网络项目,因为那没有意义。我只需要能够像我的 Web 项目一样使用 DbContext。在 web 项目中,它有启动和 DI。我不知道如何以正常方式简单地获取上下文
  • 你应该在所有项目中使用依赖注入,避免使用静态类和方法,扩展方法除外
  • 我可以像使用 Web 一样使用 DI,但不知道如何在非 Web 项目中设置 DI。似乎它是在 BuildWebHost 中设置的,我不想要它..但是是的..这是我可以研究的东西..更糟糕的情况是我将帮助程序放在我的 web 项目中,但这没有意义
  • 将您的 DbContext 放入它自己的项目中,以便您的 Web 和非 Web 项目都可以引用它。

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


【解决方案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); 

但是,理想的情况是使用依赖注入。假设您在其他项目中有一个课程CalculationService。为此,您需要将该类注册为可以注入的服务:

services.AddScoped<CalculationService>();

那么您的班级可以通过 DI 接收DbContext(或任何其他服务):

public class CalculationService
{
    private RetContext _context;

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

当然,您将无法像这样手动实例化您的类:

var service = new CalculationService();

相反,您需要使任何需要使用您的CalculationService 的类也通过 DI 接收它并使该类也可注入。

【讨论】:

  • 并且需要: var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");配置 = builder.Build(); var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
  • @punkouter 我已将其添加到代码示例中,谢谢!
猜你喜欢
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
  • 2019-06-10
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多