簡體   English   中英

System.InvalidOperationException:訪問DbContext時

[英]System.InvalidOperationException: when accessing DbContext

運行.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>();
}

你能幫忙的話,我會很高興。 我確定我做錯了什么,但我相信我已經完成了錯誤提示的所有事情。

謝謝。

您當前的Startup.cs文件已為一個數據庫( ApplicationDBContext )配置了數據庫提供程序,但沒有為您正在使用的數據庫( PartsDbContext )配置數據庫提供ApplicationDBContext

因此,添加以下行:

services.AddDbContext<PartsDbContext>(options =>  
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
)

詳細信息: https : //docs.microsoft.com/zh-cn/ef/core/miscellaneous/configuring-dbcontext#using-dbcontext-with-dependency-injection

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM