Ich weiß, dass diese Frage mehrmals gestellt wurde, aber ich habe meine Lösung noch nicht bekommen.DotNet Core, Kein Datenbankprovider wurde für diesen DbContext konfiguriert
Ich bin sehr neu in DotNet Core. Mein Problem ist, ich möchte Daten aus meiner Tabelle "Header" mit einem einfachen Linq-Befehl auswählen, aber ich sah unter Fehler.
Weitere Informationen: Für diesen DbContext wurde kein Datenbankprovider für konfiguriert. Ein Provider kann durch Überschreiben der DbContext.OnConfiguring-Methode oder mithilfe von AddDbContext für den Anwendungsdienstanbieter konfiguriert werden. Wenn AddDbContext verwendet wird, dann stellen Sie auch sicher, dass Ihr DbContext-Typ ein DbContextOptions-Objekt in seinem Konstruktor akzeptiert und es an den Basiskonstruktor für DbContext übergibt.
Mein Controller ist.
public HeaderModel GetHeaderInformation()
{
using(var context = new ApplicationDbContext())
{
var header = context.Headers.Select(x => new HeaderModel
{
colorCode = x.colorCode,
height = x.height,
Id = x.Id,
left = x.left,
top = x.top,
width = x.width
}).FirstOrDefault();
return header;
}
}
Mein ApplicationDbContext ist.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> //DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext() : base()
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
public DbSet<Header> Headers { get; set; }
public DbSet<Menu> Menus { get; set; }
}
Und meine startup.cs ist.
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddApplicationInsightsTelemetry(Configuration);
services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
services.AddMvc();
Danke für Ihre Hilfe.
Vielen Dank für Ihre Antwort, ich möchte nur meine dbContext im using-Block neu und verwenden Sie DbSet <> zum Auswählen, Hinzufügen und Löschen von Daten. Ihre Lösung ist in Ordnung, aber sie hat mein Problem nicht gelöst. –
Wie kann ich den dbcontext in die Konstruktoren von Klassen, die keine Controller sind, einfügen lassen? – zuckerthoben
@zuckerthoben hast du die Antwort auf diese Frage [hier] (https://stackoverflow.com/questions/37189984/dependency-injection-with-classes-other-than-a-controller-class) :) – 5ar