【发布时间】:2019-02-25 20:19:17
【问题描述】:
我正在尝试在我的项目中使用 Ef Core。
结构有点不同,因为我没有在 WebApi.csproj 中使用 EfCore。事实上我有一个不同的dll。和一个 DependenciesResolver.dll 来处理我所有的依赖注入。
在我的 EfCore.dll 中我都安装了
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
现在当我尝试运行命令时(我正在运行的 dll 是 EfCore.dll)
Add-Migration Name
我明白了:
访问“程序”类上的 IWebHost 时出错。 在没有应用程序服务提供商的情况下继续。错误:对象 引用未设置为对象的实例。无法创建 “StoreContext”类型的对象。添加一个实现 'IDesignTimeDbContextFactory' 到项目中,或参见 https://go.microsoft.com/fwlink/?linkid=851728 更多模式 在设计时支持。
sln的结构是这样的
WebApi | EfCore.dll | DependencyResolver.dll,我想保持这种方式,不想允许在我的 WebApi 中使用 EfCore。
这个问题的解决方法是什么?
如果这对 EfCore.dll 有帮助,我有这个。
public sealed partial class StoreContext : DbContext, IStoreContext
{
private string _connectionString;
public StoreContext(string connectionString) : base()
{
_connectionString = connectionString;
Database.EnsureCreated();
}
/// db.tbls
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddOrderConfiguration();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString);
}
}
像这样被DependencyResolver调用
private DependenciesResolver RegisterInfrastructure()
{
_serviceCollection.AddScoped<StoreContext>(factory => new StoreContext(_connectionString));
return this;
}
然后WebApi调用DependencyResolver
【问题讨论】:
标签: c# .net-core entity-framework-core asp.net-core-2.0 ef-core-2.1