bor*_*ris 1 c# entity-framework-core .net-core asp.net-core-2.0 ef-core-2.1
我正在尝试在我的项目中使用Ef Core。
就我不是在WebApi.csproj现场使用EfCore而言,结构有所不同。实际上,我有一个不同的dll。和一个DependenciesResolver.dll处理我所有的依赖项注入。
在我的EfCore.dll中,我已经安装了两个
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
现在,当我尝试运行命令时(我正在运行的dll是EfCore.dll)
Add-Migration Name
Run Code Online (Sandbox Code Playgroud)
我得到这个:
在类“ Program”上访问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);
}
}
Run Code Online (Sandbox Code Playgroud)
像这样被DependencyResolver调用
private DependenciesResolver RegisterInfrastructure()
{
_serviceCollection.AddScoped<StoreContext>(factory => new StoreContext(_connectionString));
return this;
}
Run Code Online (Sandbox Code Playgroud)
然后由WebApi调用DependencyResolver
小智 5
请看一下:https : //docs.microsoft.com/zh-cn/ef/core/miscellaneous/cli/dbcontext-creation
错误消息明确指出EF Core工具在设计时无法创建Context的实例。
如果您可以为构造函数定义不带任何参数的构造函数,那么您需要通过定义实现IDesignTimeDbContextFactory接口的类来告诉工具如何在设计时创建上下文实例。