【问题标题】:Entity cannot be configured as keyless because it is a derived type实体无法配置为无密钥,因为它是派生类型
【发布时间】:2021-05-21 14:33:15
【问题描述】:

我有一个班级ApplicationUser 和一个班级vwUserConfigvwUserConfig 是数据库中的一个视图,它包含ApplicationUser 的所有列,包括更多列。

我想要并且需要 vwUserConfigApplicationUser 继承。但是当我配置视图时:

modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");
modelBuilder.Entity<VwUserConfig>().ToView("vwUserConfig");

我收到一条错误消息,指出我无法调用 .HasNoKey(),因为它继承自 ApplicationUser

System.InvalidOperationException:“VwUserConfig”无法配置为无密钥,因为它是派生类型;必须将根类型“ApplicationUser”配置为无密钥。如果您不打算将“ApplicationUser”包含在模型中,请确保它未被上下文中的 DbSet 属性引用、在“OnModelCreating”中对 ModelBuilder 的配置调用中引用或从类型的导航中引用包含在模型中。

如果我删除 .HasNoKey(),我会收到错误:

System.InvalidOperationException:“VwUserConfig”和“ApplicationUser”都映射到“AspNetUsers”表。层次结构中没有鉴别器的所有实体类型都必须映射到不同的表。请参阅https://go.microsoft.com/fwlink/?linkid=2130430 了解更多信息。

【问题讨论】:

  • 你能按照错误信息的提示做吗? the root type 'ApplicationUser' must be configured as keyless instead
  • @RobertHarvey 我不能那样做,ApplicationUser 确实有一个键并且有自己的表。
  • 第二条错误信息是All the entity types in a hierarchy that don't have a discriminator must be mapped to different tables
  • @RobertHarvey 它被映射到不同的表。 ApplicationUser 映射到 AspNetUsers,而 vwUserConfig 映射到 vwUserConfig
  • 第二条错误信息也写着Both 'VwUserConfig' and 'ApplicationUser' are mapped to the table 'AspNetUsers' -- 为什么会这样认为?

标签: c# sql entity-framework-core


【解决方案1】:

经过一番调查,我意识到,出于某种原因,EF Core 仍然认为 VwUserConfig 应该仍然映射到 AspNetUsers,即使我正在调用 .ToView()。为了规避这个问题,我不得不这样做:

modelBuilder.Entity<VwUserConfig>().ToTable("jcudncyd").ToView("vwUserConfig");

我必须将其分配给一个随机的、不存在的表,以便将其取消映射 (?) 到 AspNetUsers。这似乎是一个错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多