我尝试在控制台 .net core 2.0 应用程序中使用 EF Core 2.0。当我使用IDesignTimeDbContextFactory
或覆盖派生类的OnConfiguring
方法时,在包管理器控制台中成功。但是,如果我尝试在 asp.net 核心应用程序中使用like,我会收到以下消息:DbContext
CustomerDbContext
Add-Migration
AddDbContext
Unable to create an object of type 'CustomerDbContext'
控制台 .net 核心应用程序的代码片段是:
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
IConfigurationRoot config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json") //needs Microsoft.Extensions.Configuration.Json
.Build();
string conn = config.GetConnectionString("WarehouseConnection");
services
.AddDbContext<CustomerDbContext>(
options => options.UseSqlServer(config.GetConnectionString("WarehouseConnection")));
var provider = services.BuildServiceProvider();
using(var context = provider.GetService<CustomerDbContext>())
{
...
}
}
}
在config.json
包含连接字符串:
{
"ConnectionStrings": {
"WarehouseConnection": "Server=(localdb)\\mssqllocaldb;Database=WAREHOUSE;Trusted_Connection=True;MultipleActiveResultSets=true"
}
该CustomerDbContext
班是:
class CustomerDbContext : DbContext
{
public CustomerDbContext(DbContextOptions<CustomerDbContext> options) : base(options) { }
public DbSet<Customer> Customers { get; set; }
}
任何想法为什么这种方法失败?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句