You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用EF Core Identity脚手架生成控制器时遇ViewModel添加DbContext错误

解决EF Core Identity脚手架生成控制器时的DbSet错误

错误信息

Error
There was an error running the selected code generator: 'Could not add Model type 'Electrical.Models.ViewModels.RegisterViewModel' to DbContext 'DataAccessLayer.AppDbContext'. Make sure that DataAccessLayer.AppDbContext' has a DbSet property for "Electrical.Models.ViewModels.RegisterViewModel".'

问题核心

RegisterViewModel是视图模型,仅用于前端注册页面的数据传递,不需要映射到数据库表,因此根本不应该被添加到AppDbContext的DbSet集合中。脚手架错误地将视图模型当作数据库实体类处理,才抛出了这个提示。

解决步骤

  • 纠正脚手架模型选择:生成控制器时,务必选择Identity的实体类(比如你自定义的ApplicationUser)作为模型,而非RegisterViewModel。如果是生成Identity管理控制器,确保关联的AppDbContext是继承了IdentityDbContext的实例,但模型必须是实体类而非视图模型。
  • 手动编写注册逻辑:如果脚手架无法正确识别模型类型,直接手动实现注册相关控制器代码,示例如下:
    public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
    
        public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }
    
        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }
    
        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            return View(model);
        }
    }
    
  • 放弃上下文工厂尝试:上下文工厂类用于设计时创建DbContext实例,和当前错误无关,无需为这个问题添加该类。

内容的提问来源于stack exchange,提问作者محمد مهدی الماسی

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:58:16