我的项目中有什么问题

Hui Liu-MSFT 48,531 信誉分 Microsoft 供应商
2024-04-18T06:00:46.3333333+00:00

我看到这个错误274070-err.jpg

EmployeeContext :

 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; }  
        }  
    }  

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; }  
    }  
}  

应用设置

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

程序

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);  
        }  
    }  
}  
  

IEmployee存储库

复制

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();  
    }  
}  

**HomeController **

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");  
        }  
    }  
}  
  


Note:此问题总结整理于:What is the problem I have in my project

Entity Framework Core
Entity Framework Core
实体框架数据访问技术的轻量型、可扩展、开源、跨平台版本。
49 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Jiale Xue - MSFT 45,006 信誉分 Microsoft 供应商
    2024-04-18T08:59:19.89+00:00

    该问题涉及您两次配置 DbContext 连接字符串:在 Program.cs 文件中和 EmployeeRepository/HomeController 构造函数方法中。

    若要解决此问题,可以使用其中之一配置连接字符串。

    如果在 program.cs 文件中配置连接字符串,请修改 EmployeeRepository 和 HomeController 构造函数方法,如下所示:

     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;  
         }  
    

    和 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;  
         }  
    

    否则,如果要从 HomeController/EmployeeRepository 配置连接字符串,可以在 Program.cs 文件中删除以下代码:

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

    如果答案是正确的解决方案,请点击“接受答案”并投赞成票。如果您对此答案有其他疑问,请点击“评论”。

    注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助

你的答案

问题作者可以将答案标记为“接受的答案”,这有助于用户了解已解决作者问题的答案。