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

Entity Framework添加Users.Email列后属性映射失败问题求助

解决Entity Framework中Users.Email属性无法映射为object类型的异常

异常信息

System.Exception: "Couldn't retrieve entities: The property 'Users.Email' could not be mapped because it is of type 'object', which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

核心问题分析

你的代码存在命名空间引用不匹配的关键问题:

  • DbContext与Users模型类都位于PlanetariumModelsFramework命名空间下
  • 但UsersRepository中引用的是PlanetariumModels命名空间下的Users类

这导致Repository使用的Users类和EF DbContext注册的DbSet<Users>并非同一类型,EF无法识别正确的属性定义,从而错误地将Email识别为object类型。

解决方案

  1. 修正命名空间引用
    修改UsersRepository的using语句,替换为模型类所在的命名空间:

    // 替换原using PlanetariumModels;
    using PlanetariumModelsFramework;
    
  2. 清理重复类
    检查项目中是否存在两个不同的Users类(分别在PlanetariumModels和PlanetariumModelsFramework下),若为误创建的冗余类,直接删除。

  3. 清理并重新编译项目

    • 删除项目的bin和obj目录
    • 重新生成整个解决方案,确保所有引用都指向同一个Users模型类

补充排查点

  • 若使用Code First模式,需创建并应用包含Email列的迁移:
    Add-Migration AddEmailToUsers
    Update-Database
    
  • 确认数据库中Users表的Email列类型为nvarchar或varchar,与模型的string类型匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:11:04