我正在尝试按照Asp.Net Core文档中的示例添加View组件。该组件使用内存数据存储。但我无法让内存工作。我不明白如何遵守错误消息中的说明。我错过了什么? 这是错误:
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
这个代码在context.add(new ToDoItem)的行中发生:
namespace ViewComponentSample.Models
{
public class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService<ToDoContext>();
if (context.Database == null)
{
throw new Exception("DB is null");
}
for (int i = 0; i < 9; i++)
{
context.Add(new TodoItem()
{
IsDone = i % 3 == 0,
Name = "Task " + (i + 1),
Priority = i % 5 + 1
});
}
context.SaveChanges();
}
}
}
我在project.json中有这些依赖项:
"dependencies": {
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
},
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.EntityFrameworkCore": "1.0.1",
"Microsoft.EntityFrameworkCore.InMemory": "1.0.1",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0",
"BundlerMinifier.Core": "2.2.281",
"Microsoft.AspNetCore.Mvc": "1.0.1",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.NETCore.App": "1.0.0",
"Microsoft.Extensions.DependencyInjection.Abstractions": "1.0.0",
"Microsoft.Extensions.DependencyInjection": "1.0.0",
"Microsoft.AspNet.Routing": "1.0.0-rc1-final"
},
这是在我的Startup.cs ConfigureServices:
中 services.AddEntityFrameworkInMemoryDatabase().AddDbContext<ToDoContext>(optionsAction => optionsAction.UseInMemoryDatabase());
这是模特:
using Microsoft.EntityFrameworkCore;
namespace ViewComponentSample.Models
{
public class ToDoContext : DbContext
{
public DbSet<TodoItem> ToDo { get; set; }
}
}
答案 0 :(得分:1)
当您在配置时调用此
...(optionsAction => optionsAction.UseInMemoryDatabase())
您只在DI中注册了DbContextOptions<ToDoContext>
的实例。但是你的ToDoContext并不知道。
例外情况表明您必须将您创建的配置注入ToDoContext。
你必须这样做:
using Microsoft.EntityFrameworkCore;
namespace ViewComponentSample.Models
{
public class ToDoContext : DbContext
{
public DbSet<TodoItem> ToDo { get; set; }
public ToDoContext(DbContextOptions options)
:base(options)
{
}
}
}
,配置将通过DI注入。
这正是异常所说的: ...如果使用AddDbContext,那么还要确保您的DbContext类型在其构造函数中接受DbContextOptions对象,并将其传递给DbContext的基础构造函数。
您已经在Startup.cs ConfigureServices()中使用了AddDbContext()
,因此必须满足条件如果使用了AddDbContext ,则必须满足。
详细了解DbContext配置here。
希望这有帮助,
此致