【发布时间】: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