SQL Server Entity Framework Core keeps throwing error "'No database provider has been configured for this DbContext"

pxq42qpu  于 2023-02-28  发布在  其他
关注(0)|答案(1)|浏览(179)

I am about to go insane. I am studying software engineering and we are doing C# with .NET currently. So we are supposed to use Entity Framework to create and send/receive data from a database locally on our PC with SQL Server.

I have created to the best of my ability the exact same code as my teacher but nothing I do will allow me to send anything to the database at all. I get an error
No Database provider has been configured for this DBContexts

My teacher is using

void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

to do this, and it just isn't working for me.

I would like to use that way, but after asking ChatGPT I am aware of using something called addDbcontext which I have also tried but didn't work.

It seems like the code I have CAN create a database with the connection string I provided, but it won't allow me to send data with a

protected override void OnModelCreating(ModelBuilder modelBuilder)

So if ANYONE can tell me what i am doing wrong, with this Entity Framework and SQL Server, I would be so grateful!

DBContext class

using Microsoft.EntityFrameworkCore;
using Opgave1.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Opgave1.DBHandle
{
    public class SkoleKlasseContext : DbContext
    {
        public SkoleKlasseContext() 
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Data Source=DESKTOP-5CSHCTM\\SQLEXPRESS; Initial Catalog = Skoleklasse1; Integrated Security = SSPI; TrustServerCertificate = true");
        }
        
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<SkoleKlasse>().HasData(new SkoleKlasse[] { new SkoleKlasse { KlasseID = -1, KlasseNavn = "21T", Lokale = "A1.23", SpecialKlase = false } });
        }

        public DbSet<SkoleKlasse> skoleKlasser { get; set; }
    }
}

Main class

public partial class MainWindow : Window
{
    private SkoleKlasseContext context = new SkoleKlasseContext();

    public MainWindow()
    {
        InitializeComponent();

        // Call EnsureCreated to create the database if it does not exist
        bool created = context.Database.EnsureCreated();

        if (created)
        {
            MessageBox.Show("Database created");
        }
    }
}
h43kikqp

h43kikqp1#

I think the SkoleKlasseContext requires a parameter of type DbContextOptions. Try adding this parameter and passing it to the base DbContext object you're inheriting from

public SkoleKlasseContext(DbContextOptions options) : base(options)
{
}

相关问题