You need to enable JavaScript to run this app. C# MVC开发遇CS0051报错:CharityDbContext可访问性低于方法
优惠活动
大模型
产品
解决方案
定价
更多

C# MVC开发遇CS0051报错:CharityDbContext可访问性低于方法

问题根因

你定义的DbContext类名为CharityContext,但控制器代码中所有引用该上下文的位置都错误写为不存在的CharityDbContext。编译器无法找到你声明的CharityDbContext类型,默认将其识别为内部(internal)访问级别,和public修饰的控制器构造函数访问级别不一致,因此触发CS0051错误。
你之前修改字段访问性的操作和错误无关,不需要保留,private readonly才是依赖注入字段的最佳实践。

解决步骤
  • 替换控制器中所有CharityDbContext为正确的CharityContext,修改后的控制器核心代码如下:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using WebApplication5.Models;    

namespace WebApplication5.Controllers
{
    public class Campaign : Controller
    {
        private readonly CharityContext _db;

        public Campaign(CharityContext db)
        {
            _db = db;
        }

        public IActionResult Details()
        {
            //IEnumerable<Campaign> objList = _db.CampaignName;
            return View();
        }
    }
}
  • 确认项目启动文件中已经完成CharityContext的依赖注入注册,.NET 6+版本的Program.cs参考注册代码如下:
builder.Services.AddDbContext<CharityContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("CharityDbConnection")));
  • 重新编译项目即可解决报错。

内容的提问来源于stack exchange,提问作者Davea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 03:24:02