Home > Enterprise >  Dependency injection of Database context error
Dependency injection of Database context error

Time:07-31

Hello I am trying to create an instance of the db in the constructor of the controller to be able to use it throughout the controller but it keep throwing an error.

This is the error I am getting:

InvalidOperationException: Unable to resolve service for type 'Darkcrow_Dashboard.Model.ApplicationDbContext' while attempting to activate 'Darkcrow_Dashboard.Controllers.DashboardController'.

This is the applicationdbcontext.cs:

using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace Darkcrow_Dashboard.Model
{
    public partial class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext()
        {
        }

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Artifact> Artifacts { get; set; } = null!;
        public virtual DbSet<ArtifactSize> ArtifactSizes { get; set; } = null!;
        public virtual DbSet<AspNetRole> AspNetRoles { get; set; } = null!;
        public virtual DbSet<AspNetRoleClaim> AspNetRoleClaims { get; set; } = null!;
        public virtual DbSet<AspNetUser> AspNetUsers { get; set; } = null!;
        public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; } = null!;
        public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; } = null!;
        public virtual DbSet<AspNetUserToken> AspNetUserTokens { get; set; } = null!;
        public virtual DbSet<Dcplayer> Dcplayers { get; set; } = null!;
        public virtual DbSet<Dcvillage> Dcvillages { get; set; } = null!;
        public virtual DbSet<DefensiveForm> DefensiveForms { get; set; } = null!;
        public virtual DbSet<OtherPlayer> OtherPlayers { get; set; } = null!;
        public virtual DbSet<OtherVillage> OtherVillages { get; set; } = null!;
        public virtual DbSet<Vagon> Vagons { get; set; } = null!;

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                optionsBuilder.UseSqlServer("Server=localhost\\SQLEXPRESS;Database=DarkCrow;Trusted_Connection=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Artifact>(entity =>
            {
                entity.HasKey(e => e.ArtifactName);

                entity.ToTable("Artifact");

                entity.Property(e => e.ArtifactName)
                    .HasMaxLength(45)
                    .IsUnicode(false);

                entity.HasMany(d => d.Sizes)
                    .WithMany(p => p.ArtifactNames)
                    .UsingEntity<Dictionary<string, object>>(
                        "ArtifactArtifactSize",
                        l => l.HasOne<ArtifactSize>().WithMany().HasForeignKey("Size").OnDelete(DeleteBehavior.ClientSetNull).HasConstraintName("FK_Multi_ArtifactSize_Artifact"),
                        r => r.HasOne<Artifact>().WithMany().HasForeignKey("ArtifactName").OnDelete(DeleteBehavior.ClientSetNull).HasConstraintName("FK_Multi_Artifact_ArtifactSize"),
                        j =>
                        {
                            j.HasKey("ArtifactName", "Size");

                            j.ToTable("Artifact_ArtifactSize");

                            j.IndexerProperty<string>("ArtifactName").HasMaxLength(45).IsUnicode(false);

                            j.IndexerProperty<string>("Size").HasMaxLength(10).IsUnicode(false);
                        });
            });

            modelBuilder.Entity<ArtifactSize>(entity =>
            {
                entity.HasKey(e => e.Size);

                entity.ToTable("ArtifactSize");

                entity.Property(e => e.Size)
                    .HasMaxLength(10)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<AspNetRole>(entity =>
            {
                entity.HasIndex(e => e.NormalizedName, "RoleNameIndex")
                    .IsUnique()
                    .HasFilter("([NormalizedName] IS NOT NULL)");

                entity.Property(e => e.Name).HasMaxLength(256);

                entity.Property(e => e.NormalizedName).HasMaxLength(256);
            });

            modelBuilder.Entity<AspNetRoleClaim>(entity =>
            {
                entity.HasIndex(e => e.RoleId, "IX_AspNetRoleClaims_RoleId");

                entity.HasOne(d => d.Role)
                    .WithMany(p => p.AspNetRoleClaims)
                    .HasForeignKey(d => d.RoleId);
            });

            modelBuilder.Entity<AspNetUser>(entity =>
            {
                entity.HasIndex(e => e.NormalizedEmail, "EmailIndex");

                entity.HasIndex(e => e.NormalizedUserName, "UserNameIndex")
                    .IsUnique()
                    .HasFilter("([NormalizedUserName] IS NOT NULL)");

                entity.Property(e => e.Email).HasMaxLength(256);

                entity.Property(e => e.NormalizedEmail).HasMaxLength(256);

                entity.Property(e => e.NormalizedUserName).HasMaxLength(256);

                entity.Property(e => e.UserName).HasMaxLength(256);

                entity.HasMany(d => d.Roles)
                    .WithMany(p => p.Users)
                    .UsingEntity<Dictionary<string, object>>(
                        "AspNetUserRole",
                        l => l.HasOne<AspNetRole>().WithMany().HasForeignKey("RoleId"),
                        r => r.HasOne<AspNetUser>().WithMany().HasForeignKey("UserId"),
                        j =>
                        {
                            j.HasKey("UserId", "RoleId");

                            j.ToTable("AspNetUserRoles");

                            j.HasIndex(new[] { "RoleId" }, "IX_AspNetUserRoles_RoleId");
                        });
            });

            modelBuilder.Entity<AspNetUserClaim>(entity =>
            {
                entity.HasIndex(e => e.UserId, "IX_AspNetUserClaims_UserId");

                entity.HasOne(d => d.User)
                    .WithMany(p => p.AspNetUserClaims)
                    .HasForeignKey(d => d.UserId);
            });

            modelBuilder.Entity<AspNetUserLogin>(entity =>
            {
                entity.HasKey(e => new { e.LoginProvider, e.ProviderKey });

                entity.HasIndex(e => e.UserId, "IX_AspNetUserLogins_UserId");

                entity.Property(e => e.LoginProvider).HasMaxLength(128);

                entity.Property(e => e.ProviderKey).HasMaxLength(128);

                entity.HasOne(d => d.User)
                    .WithMany(p => p.AspNetUserLogins)
                    .HasForeignKey(d => d.UserId);
            });

            modelBuilder.Entity<AspNetUserToken>(entity =>
            {
                entity.HasKey(e => new { e.UserId, e.LoginProvider, e.Name });

                entity.Property(e => e.LoginProvider).HasMaxLength(128);

                entity.Property(e => e.Name).HasMaxLength(128);

                entity.HasOne(d => d.User)
                    .WithMany(p => p.AspNetUserTokens)
                    .HasForeignKey(d => d.UserId);
            });

            modelBuilder.Entity<Dcplayer>(entity =>
            {
                entity.ToTable("DCPlayer");

                entity.HasIndex(e => e.Username, "UQ__DCPlayer__536C85E41EFBF1E2")
                    .IsUnique();

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("ID");

                entity.Property(e => e.Username)
                    .HasMaxLength(20)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<Dcvillage>(entity =>
            {
                entity.ToTable("DCVillage");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("ID");

                entity.Property(e => e.DcplayerId).HasColumnName("DCPlayer_ID");

                entity.Property(e => e.VillageName)
                    .HasMaxLength(40)
                    .IsUnicode(false);

                entity.Property(e => e.Xcoordinate).HasColumnName("XCoordinate");

                entity.Property(e => e.Ycoordinate).HasColumnName("YCoordinate");

                entity.HasOne(d => d.Dcplayer)
                    .WithMany(p => p.Dcvillages)
                    .HasForeignKey(d => d.DcplayerId)
                    .HasConstraintName("FK_TEST");
            });

            modelBuilder.Entity<DefensiveForm>(entity =>
            {
                entity.HasKey(e => e.FormId)
                    .HasName("PK_formID");

                entity.ToTable("DefensiveForm");

                entity.Property(e => e.FormId).HasColumnName("formID");

                entity.Property(e => e.ArtifactName)
                    .HasMaxLength(45)
                    .IsUnicode(false)
                    .HasColumnName("Artifact_Name");

                entity.Property(e => e.CalculatedPt).HasColumnName("CalculatedPT");

                entity.Property(e => e.DcplayerId).HasColumnName("DCPlayer_ID");

                entity.Property(e => e.OtherPlayerId).HasColumnName("OtherPlayer_ID");

                entity.Property(e => e.Pt).HasColumnName("PT");

                entity.HasOne(d => d.ArtifactNameNavigation)
                    .WithMany(p => p.DefensiveForms)
                    .HasForeignKey(d => d.ArtifactName)
                    .OnDelete(DeleteBehavior.Cascade)
                    .HasConstraintName("FK_Artifact_DeffForm");

                entity.HasOne(d => d.Dcplayer)
                    .WithMany(p => p.DefensiveForms)
                    .HasForeignKey(d => d.DcplayerId)
                    .HasConstraintName("FK_DCPlayer_DeffForm");

                entity.HasOne(d => d.OtherPlayer)
                    .WithMany(p => p.DefensiveForms)
                    .HasForeignKey(d => d.OtherPlayerId)
                    .HasConstraintName("FK_OtherPlayer_DeffForm");
            });

            modelBuilder.Entity<OtherPlayer>(entity =>
            {
                entity.ToTable("OtherPlayer");

                entity.HasIndex(e => e.Username, "UQ__OtherPla__536C85E4BF7EA2E1")
                    .IsUnique();

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("ID");

                entity.Property(e => e.Alliance)
                    .HasMaxLength(10)
                    .IsUnicode(false);

                entity.Property(e => e.Username)
                    .HasMaxLength(20)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<OtherVillage>(entity =>
            {
                entity.ToTable("OtherVillage");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("ID");

                entity.Property(e => e.OtherPlayerId).HasColumnName("OtherPlayer_ID");

                entity.Property(e => e.VillageName)
                    .HasMaxLength(40)
                    .IsUnicode(false);

                entity.Property(e => e.Xcoordinate).HasColumnName("XCoordinate");

                entity.Property(e => e.Ycoordinate).HasColumnName("YCoordinate");

                entity.HasOne(d => d.OtherPlayer)
                    .WithMany(p => p.OtherVillages)
                    .HasForeignKey(d => d.OtherPlayerId)
                    .HasConstraintName("FK_Village_OtherPlayer");
            });

            modelBuilder.Entity<Vagon>(entity =>
            {
                entity.ToTable("Vagon");

                entity.Property(e => e.Id).HasColumnName("ID");

                entity.Property(e => e.DefensiveFormId).HasColumnName("DefensiveForm_ID");

                entity.Property(e => e.VagonTime).HasColumnType("datetime");

                entity.HasOne(d => d.DefensiveForm)
                    .WithMany(p => p.Vagons)
                    .HasForeignKey(d => d.DefensiveFormId)
                    .HasConstraintName("FK_DeffForm_Vagon");
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

This is the controller where I want to inject the dependency of the db

using Darkcrow_Dashboard.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace Darkcrow_Dashboard.Controllers
{
    [Authorize]
    public class DashboardController : Controller
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly ApplicationDbContext _db;

        public DashboardController(UserManager<IdentityUser> userManager, ApplicationDbContext db)
        {
            _userManager = userManager;
            _db = db;
        }

        public async Task<IActionResult> Index()
        {

            return View();
        }

        public IActionResult Defensivo()
        {
            return View();
        }

        public IActionResult Artefacto()
        {
            return View();
        }
    }
}

This is my file explorer

This is the full error

CodePudding user response:

It looks like your context is not added to the DI container.

Here's a snippet from EntityFrameworkServiceCollectionExtensions.AddDbContext Method:

public void ConfigureServices(IServiceCollection services)
{
   var connectionString = "connection string to database";

   services.AddDbContext<MyContext>(options => >options.UseSqlServer(connectionString));
}

CodePudding user response:

When you are using UserManager in your controller, You must Inherit your DBContext from the IdentityDbContext.

public partial class ApplicationDbContext : IdentityDBContext<IdentityUser>
  • Related