0

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

BUIBBE
  • 23
  • 1
  • 7
  • A dbContext is class data that is mapped to a database. There is an edmx file that contains the mapping. The dbContext classes have to be the same in the client that sends the HTTP request and the server that receives the dbContext for code to work. The dbContext in this case is data that is contained in the body of the request/response. A controller can be either in the client or server that processes the HTYTP message. From code I cannot tell if you controller is in client or server but it doesn't make a difference. dbContext classes have to be defined exactly the same in client and server. – jdweng Jul 30 '22 at 21:16
  • When you have a controller at both client and server the following occurs 1) Client serializes data and uses a Put to send data in the body of request 2) server receives message with GET and deserializes the data in body 3) Server process the request 4) Server serializes the data and uses a Put to send data in the body of the response 5) Client receives the response and deserializes the data in the body. A controller can be used either in client, server or both. A request/response body is optional so a request/response can or cannot have data in the body. – jdweng Jul 30 '22 at 21:21
  • I am able to log in and out and register as well which are using the applicationdbcontext to communicate with the database, therefore as far as I understand the applicationdbcontext is correct. – BUIBBE Jul 30 '22 at 21:21
  • Did you give us the *full* exception details, including inner exceptions? – mason Jul 30 '22 at 21:44
  • You have a two port application. Port 1 is an HTTP connection between client and server where you are using a controller. Port 2 is a connection between the server and the database. You error is in Port 1 not Port 2 which between server and database. – jdweng Jul 30 '22 at 21:56

3 Answers3

0

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));
}
tymtam
  • 31,798
  • 8
  • 86
  • 126
0

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

public partial class ApplicationDbContext : IdentityDBContext<IdentityUser>
0

At first, add your Db context to startUp ConfigureServices method as "tymtam" said , than register your identity in ConfigureServices like this :

services.AddIdentity<ApplicationUser, IdentityRole>();

than inherit your context from IdentityDbContext

Apollo13
  • 11
  • 6