【发布时间】:2017-05-03 12:30:35
【问题描述】:
运行 .Net Core 应用程序时出现错误。我开始访问 DbContext 并弹出这个
System.InvalidOperationException: '没有为此 DbContext 配置数据库提供程序。可以通过覆盖 DbContext.OnConfiguring 方法或在应用程序服务提供者上使用 AddDbContext 来配置提供者。如果使用了 AddDbContext,则还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象并将其传递给 DbContext 的基本构造函数。'
我已经尝试修复它,但它仍然出现。
DbContext.cs
public class PartsDbContext : DbContext
{
public DbSet<Tower> Towers { get; set; }
public DbSet<Motherboard> Motherboards { get; set; }
public PartsDbContext(DbContextOptions<PartsDbContext> options)
: base(options)
{
}
}
Controller.cs
public class AdminController : Controller
{
private readonly PartsDbContext _context;
public AdminController(PartsDbContext context)
{
_context = context;
}
public IActionResult Index()
{
if (User.Identity.Name == null)
{
return RedirectToAction("Register", "Account");
}
return View();
}
public IActionResult Towers()
{
var model = _context.Towers.ToList();
return View(model);
}
public IActionResult Motherboards()
{
var model = _context.Motherboards.ToList();
return View(model);
}
}
错误显示在 Towers() 中的这一行
var model = _context.Towers.ToList();
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddEntityFramework()
.AddDbContext<PartsDbContext>();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
任何帮助都会很好。我确定我做错了什么,但我相信我已经做了错误提示的所有事情。
谢谢。
【问题讨论】:
-
您是否真的在
App.config中配置了DefaultConnection? -
没有 App.config。我正在使用 ASP.Net Core 1.1,但我不相信它使用 App.config
-
抱歉,
appsettings.json。见docs.microsoft.com/en-us/ef/core/miscellaneous/… -
啊是的,它说这个“DefaultConnection”:“Server=(localdb)\\mssqllocaldb;Database=aspnet-PrecisionCustomPC-b14db89e-86ad-4855-a17f-ac64a04339aa;Trusted_Connection=True;MultipleActiveResultSets=true "
标签: c# entity-framework dbcontext asp.net-core-1.1