What is the problem I have in my project

SparkCore 21 Reputation points
2022-12-26T19:44:37.22+00:00

I SEE THIS ERROR 274070-err.jpg

my dbContext :

 using Microsoft.EntityFrameworkCore;  
    using System.Collections.Generic;  
    using System.Reflection.Metadata;  
    using RepositoryPattern.Models;  
    namespace RepositoryPattern.Data  
    {  
        public class EmployeeContext:DbContext  
        {  
        public EmployeeContext(DbContextOptions<EmployeeContext> options): base(options)  
            {   
              
            }  
      
       public DbSet<Employee> Employees { get; set; }  
        }  
    }  

My Model

using System.ComponentModel.DataAnnotations;  
using System.Xml.Linq;  
  
namespace RepositoryPattern.Models  
{  
    public partial class Employee  
    {  
        public int Id { get; set; }  
  
        [Required(ErrorMessage = "Please enter first name")]  
        [Display(Name = "First Name")]  
        public string FirstName { get; set; }  
  
        [Required(ErrorMessage = "Please enter last name")]  
        [Display(Name = "Last Name")]  
        public string LastName { get; set; }  
  
        [Required(ErrorMessage = "Please enter age")]  
        public Nullable<int> Age { get; set; }  
  
        [Required(ErrorMessage = "Please enter position")]  
        public string Position { get; set; }  
  
        [Required(ErrorMessage = "Please enter office")]  
        public string Office { get; set; }  
  
        [Required(ErrorMessage = "Please enter salary")]  
        public Nullable<int> Salary { get; set; }  
    }  
}  

appsettings

{  
  "ConnectionStrings": {  
    "DefaultConnection": "Server=DESKTOP-O8HUSHS;Database=EmployeeDB;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"  
  },  
  "Logging": {  
    "LogLevel": {  
      "Default": "Information",  
      "Microsoft.AspNetCore": "Warning"  
    }  
  },  
  "AllowedHosts": "*"  
}  
  

Program

using Microsoft.EntityFrameworkCore;  
using RepositoryPattern.Data;  
using RepositoryPattern.Repositories;  
  
var builder = WebApplication.CreateBuilder(args);  
  
// Add services to the container.  
builder.Services.AddControllersWithViews();  
builder.Services.AddSingleton<IEmployeeRepository, EmployeeRepository>();  
//builder.Services.AddTransient<IEmployeeRepository, EmployeeRepository>();     
// Add services to the container.  
builder.Services.AddDbContext<EmployeeContext>(options =>  
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));  
  
  
var app = builder.Build();  
  
// Configure the HTTP request pipeline.  
if (!app.Environment.IsDevelopment())  
{  
    app.UseExceptionHandler("/Home/Error");  
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
    app.UseHsts();  
}  
  
app.UseHttpsRedirection();  
app.UseStaticFiles();  
  
app.UseRouting();  
  
app.UseAuthorization();  
  
app.MapControllerRoute(  
    name: "default",  
    pattern: "{controller=Home}/{action=Index}/{id?}");  
  
app.Run();  
  
  

EmployeeRepository

using Microsoft.EntityFrameworkCore;  
using RepositoryPattern.Data;  
using RepositoryPattern.Models;  
  
namespace RepositoryPattern.Repositories  
{  
    public class EmployeeRepository : IEmployeeRepository  
    {  
        private readonly EmployeeContext _dbContext;  
  
        private readonly IConfiguration _configuration;  
        private string _connectionString;  
        DbContextOptionsBuilder<EmployeeContext> _optionsBuilder;  
  
        public EmployeeRepository(IConfiguration configuration)  
        {  
            _configuration = configuration;  
            _optionsBuilder = new DbContextOptionsBuilder<EmployeeContext>();  
            _connectionString = _configuration.GetConnectionString("DefaultConnection");  
            _optionsBuilder.UseSqlServer(_connectionString);  
            _dbContext = new EmployeeContext(_optionsBuilder.Options);  
        }  
        public EmployeeRepository(EmployeeContext context)  
        {  
            _dbContext = context;  
        }  
  
        public IEnumerable<Employee> GetEmployees()  
        {  
            return _dbContext.Employees.ToList();  
        }  
  
        public Employee GetEmployeeById(int id)  
        {  
            return _dbContext.Employees.Find(id);  
        }  
  
        public void NewEmployee(Employee employee)  
        {  
            _dbContext.Employees.Add(employee);  
            Save();  
        }  
  
        public void UpdateEmployee(Employee employee)  
        {  
            _dbContext.Entry(employee).State = EntityState.Modified;  
        }  
  
        public void DeleteEmployee(int id)  
        {  
            var employee = _dbContext.Employees.Find(id);  
            if (employee != null) _dbContext.Employees.Remove(employee);  
        }  
  
        public void Save()  
        {  
            _dbContext.SaveChanges();  
        }  
  
        private bool _disposed = false;  
  
        protected virtual void Dispose(bool disposing)  
        {  
            if (!this._disposed)  
            {  
                if (disposing)  
                {  
                    _dbContext.Dispose();  
                }  
            }  
            this._disposed = true;  
        }  
        public void Dispose()  
        {  
            Dispose(true);  
            GC.SuppressFinalize(this);  
        }  
    }  
}  
  

IEmployeeRepository

using RepositoryPattern.Models;  
  
namespace RepositoryPattern.Repositories  
{  
    public interface IEmployeeRepository  
    {  
        IEnumerable<Employee> GetEmployees();  
        Employee GetEmployeeById(int id);  
        void NewEmployee(Employee employee);  
        void UpdateEmployee(Employee employee);  
        void DeleteEmployee(int id);  
        void Save();  
    }  
}  

Home Controller

using Microsoft.AspNetCore.Mvc;  
using Microsoft.EntityFrameworkCore;  
using RepositoryPattern.Data;  
using RepositoryPattern.Models;  
using RepositoryPattern.Repositories;  
using System.Diagnostics;  
  
namespace RepositoryPattern.Controllers  
{  
    public class HomeController : Controller  
    {  
        private readonly EmployeeContext _dbContext;  
  
        private readonly IConfiguration _configuration;  
        private string _connectionString;  
        DbContextOptionsBuilder<EmployeeContext> _optionsBuilder;  
        private readonly IEmployeeRepository _employeeRepository;  
  
        public HomeController(IConfiguration configuration)  
        {  
            _configuration = configuration;  
            _optionsBuilder = new DbContextOptionsBuilder<EmployeeContext>();  
            _connectionString = _configuration.GetConnectionString("DefaultConnection");  
            _optionsBuilder.UseSqlServer(_connectionString);  
            _employeeRepository = new EmployeeRepository(new EmployeeContext(_optionsBuilder.Options));  
        }  
  
        public HomeController(IEmployeeRepository employeeRepository)  
        {  
            _employeeRepository = employeeRepository;  
        }  
  
        public ActionResult Index()  
        {  
            var employee = _employeeRepository.GetEmployees();  
            return View(employee);  
        }  
  
        public ActionResult Details(int id)  
        {  
            var employee = _employeeRepository.GetEmployeeById(id);  
            return View(employee);  
        }  
  
        public ActionResult Create()  
        {  
            return View();  
        }  
  
        [HttpPost]  
        [ValidateAntiForgeryToken]  
        public ActionResult Create(Employee employee)  
        {  
            if (ModelState.IsValid)  
            {  
                _employeeRepository.NewEmployee(employee);  
                _employeeRepository.Save();  
                return RedirectToAction("Index");  
            }  
            return View();  
        }  
  
        [HttpGet]  
        public ActionResult Edit(int id)  
        {  
            var employee = _employeeRepository.GetEmployeeById(id);  
            return View(employee);  
        }  
  
        [HttpPost]  
        public ActionResult Edit(Employee employee)  
        {  
            if (ModelState.IsValid)  
            {  
                _employeeRepository.UpdateEmployee(employee);  
                _employeeRepository.Save();  
                return RedirectToAction("Index", "Home");  
  
            }  
            else  
            {  
                return View(employee);  
            }  
        }  
  
        [HttpGet]  
        public ActionResult Delete(int id)  
        {  
            var employee = _employeeRepository.GetEmployeeById(id);  
            return View(employee);  
        }  
  
        [HttpPost]  
        public ActionResult ConfirmDelete(int id)  
        {  
            _employeeRepository.DeleteEmployee(id);  
            _employeeRepository.Save();  
            return RedirectToAction("Index", "Home");  
        }  
    }  
}  
  

I ATTACH THE PROJECT CLICK LINK

h0gvwo

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,162 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-12-27T06:02:17.94+00:00

    Hi @SparkCore ,

    The issue relates that you configure the DbContext Connection String twice: in the Program.cs file and the EmployeeRepository/HomeController constructor methods.

    To solve this issue, you can configure the Connection string use one of them.

    If you configure the connection string in the program.cs file, modify the EmployeeRepository and HomeController constructor methods as below:

     public class EmployeeRepository : IEmployeeRepository  
     {  
         private readonly EmployeeContext _dbContext;  
      
         //private readonly IConfiguration _configuration;  
         //private string _connectionString;  
         //DbContextOptionsBuilder<EmployeeContext> _optionsBuilder;  
         //remove this method.  
         //public EmployeeRepository(IConfiguration configuration)  
         //{  
         //    _configuration = configuration;  
         //    _optionsBuilder = new DbContextOptionsBuilder<EmployeeContext>();  
        //    _connectionString = _configuration.GetConnectionString("DefaultConnection");  
        //     _optionsBuilder.UseSqlServer(_connectionString);  
        //     _dbContext = new EmployeeContext(_optionsBuilder.Options);  
        // }  
         public EmployeeRepository(EmployeeContext context)  
         {  
             _dbContext = context;  
         }  
    

    and the HomeController:

     public class HomeController : Controller  
     {  
         private readonly EmployeeContext _dbContext;  
      
         //private readonly IConfiguration _configuration;  
         //private string _connectionString;  
        // DbContextOptionsBuilder<EmployeeContext> _optionsBuilder;  
         private readonly IEmployeeRepository _employeeRepository;  
         //remove this method  
         //public HomeController(IConfiguration configuration)  
         //{  
         //    _configuration = configuration;  
         //    _optionsBuilder = new DbContextOptionsBuilder<EmployeeContext>();  
         //    _connectionString = _configuration.GetConnectionString("DefaultConnection");  
         //    _optionsBuilder.UseSqlServer(_connectionString);  
        //     _employeeRepository = new EmployeeRepository(new EmployeeContext(_optionsBuilder.Options));  
        // }  
      
         public HomeController(IEmployeeRepository employeeRepository)  
         {  
             _employeeRepository = employeeRepository;  
         }  
    

    Otherwise, if you want to configure the connection string from the HomeController/EmployeeRepository, you can remove the following code in the Program.cs file:

     builder.Services.AddDbContext<EmployeeContext>(options =>  
     options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion


1 additional answer

Sort by: Most helpful
  1. AgaveJoe 26,201 Reputation points
    2022-12-26T20:37:32.143+00:00

    Declare the EmployeeContext before the repository service.

    0 comments No comments