使用 Entity Framework Core 和 ASP.NET Core Identity 的 ASP.NET MVC 上出现 InvalidOperationException

问题描述 投票:0回答:1

我正在使用 Entity Framework Core 和 ASP.NET Core Identity 在 ASP.NET MVC 上制作一个项目。将所有更改应用到我的编辑后(使用 CRUD),我在以下行中收到此错误消息:

var existingProduct = _context.Products.Find(id);

System.InvalidOperationException:“尚未为此 DbContext 配置数据库提供程序。可以通过重写“DbContext.OnConfiguring”方法或在应用程序服务提供程序上使用“AddDbContext”来配置提供程序。如果使用“AddDbContext”,则还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象,并将其传递给 DbContext 的基本构造函数。'

这是ProductsController中编辑功能的代码:

[HttpPost]
[Route("edit/{id}")]
[ValidateAntiForgeryToken]
public IActionResult Edit(int id, Product model)
{
    using (var _context = new ApplicationDbContext())
    {
        var existingProduct = _context.Products.Find(id);
        if (existingProduct == null)
        {
            return NotFound();
        }

        if (this.ModelState.IsValid)
        {
            existingProduct.Name = model.Name;
            existingProduct.Stock = model.Stock;
            existingProduct.Price = model.Price;
            existingProduct.ImageUrl = model.ImageUrl;
            _context.SaveChanges();

            return Redirect("/");
        }
        return RedirectToAction("Index", "Products");
    }
}

现在这是我的 ApplicationDbContext.cs 文件:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
        {
        }
        

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
        public DbSet<Product> Products { get; set; }
        public DbSet<Order> Orders { get; set; }
    }

最后是我的 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(   
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDatabaseDeveloperPageExceptionFilter();

    services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddControllersWithViews();
}

因为我确信您注意到我有一个空的构造函数,所以这就是我实际上拥有它的原因。在没有这个空的构造函数时,我收到此错误消息:

错误CS7036没有给出与“ApplicationDbContext.ApplicationDbContext(DbContextOptions)”所需参数“选项”相对应的参数

调用ApplicationDbContext的行上给出了错误

        [HttpGet]
        [Route("edit/{id}")]
        public IActionResult Edit(int id)
        {
            using (var _context = new ApplicationDbContext())
            {
                {
                    var product = this._context.Products.Find(id);
                    if (product == null)
                    {
                        return NotFound();
                    }
                    return View(product);
                }
            }
 [HttpPost]
 [Route("edit/{id}")]
 [ValidateAntiForgeryToken]
 public IActionResult Edit(int id, Product model)
 {
    using (var _context = new ApplicationDbContext())
     {
         var existingProduct = _context.Products.Find(id);
         if (existingProduct == null)
         {
             return NotFound();
         }

         if (this.ModelState.IsValid)
         {
             existingProduct.Name = model.Name;
             existingProduct.Stock = model.Stock;
             existingProduct.Price = model.Price;
             existingProduct.ImageUrl = model.ImageUrl;
             _context.SaveChanges();

             return Redirect("/");
         }
         return RedirectToAction("Index", "Products");
     }
 }
c# asp.net-core-mvc crud asp.net-core-identity
1个回答
0
投票

您在代码中实例化

ApplicationDbContext
的新实例,而没有传递启动类最终将传递它的
DbContextOptions<T>
。尝试在控制器类中使用依赖注入。

public class SomeController : Controller
{
    private readonly ApplicationDbContext _context;
    public SomeController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    [Route("edit/{id}")]
    public IActionResult Edit(int id)
    {
        var product = this._context.Products.Find(id);
        //Rest of code 
    }
}

这将接受来自启动的应用程序数据库上下文。

© www.soinside.com 2019 - 2024. All rights reserved.