【问题标题】:EF Core 2.0.1 Using IdentityUser as navigation propertyEF Core 2.0.1 使用 IdentityUser 作为导航属性
【发布时间】:2018-03-03 20:53:05
【问题描述】:

当我尝试注册用户或创建迁移时,我收到以下错误:

“无法在 'ApplicationUser' 上配置密钥,因为它是 派生类型。必须在根类型上配置密钥 '身份用户'。如果您不打算使用“IdentityUser” 包含在模型中,确保它不包含在 DbSet 中 上下文中的属性,在配置调用中引用 模型构建器,或从某个类型的导航属性中引用 包含在模型中。”

我有一个 BaseEntity,一切都来自这样:

public class BaseEntity
    {
        public int Id { get; set; }

        [Required]
        public DateTime DateCreated { get; set; }

        [Required]
        public DateTime DateModified { get; set; }

        [Required]
        public string CreatedById { get; set; }

        [Required]
        public string ModifiedById { get; set; }

        public virtual IdentityUser CreatedBy { get; set; }
        public virtual IdentityUser ModifiedBy { get; set; }
    }

public class FilePath : BaseEntity, IAuditable
    {
        [StringLength(255)]
        public string FileName { get; set; }
        public FileType FileType { get; set; }
    }

是否有新规则或更新表明您不能将 IdentityUser 用作导航属性? Google 并没有带来太多有用的信息。

整个解决方案是here 如果需要。

更新:升级到 2.0.1 预览版后,这些错误更有帮助:

外键属性 {'Id' : string} 的最佳匹配是 与主键 {'Id' : int} 不兼容。

【问题讨论】:

  • 我认为您的意思是 2.1 预览版。相同的错误消息,但我使用脚手架从数据库构建模型。
  • incompatible 消息我相信会消失,它只是 info 而不是错误。我想虽然你可能还有一个问题。 github.com/aspnet/EntityFrameworkCore/issues/10918

标签: asp.net asp.net-mvc entity-framework entity-framework-core


【解决方案1】:

我遇到了同样的问题。您需要将代码中使用 BaseEntity 的所有位置替换为 FilePath。

示例: 我有这样的继承:

public class ApplicationUser : IdentityUser
    {

    }

我改变了 ApplicationDbContext 像:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {

        }


        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }

但我遇到了同样的异常。

在我将代码中的 IdentityUser 替换为 ApplicationUser 后,错误消失了。我认为您应该在数据访问层中使用 BaseEntityFilePath

【讨论】:

    【解决方案2】:

    回复。 "外键属性的最佳匹配 {'Id' : string}..."

    您的 ApplicationUser 类未指定其 Id 字段的类型。在这种情况下,它默认为string。你可以做的——尽管这会导致你重建你的数据库,所以现在可能为时已晚——显式输入ApplicationUser

    public class ApplicationUser: IdentityUser<int>
    {
        // myUser.Id is now an int
    }
    

    IdentityUser docs

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 2022-09-23
      • 2022-01-01
      • 2018-05-09
      • 2018-10-22
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多