EF7迁移 - 实体类型''的相应CLR类型不可实例化

Rov*_*ret 8 c# entity-framework entity-framework-core asp.net-core

我正在尝试使用EF7迁移,并在使用继承建模组织模型时遇到困难.

组织是一个抽象类,有两个继承它的具体类叫做Individual和Company.

我在DbContext中将组织抽象类设置为DbSet并运行迁移.

我在这里关注本教程

显示以下错误:

实体类型"组织"的相应CLR类型不可实例化,并且模型中没有与具体CLR类型对应的派生实体类型.

我该怎么办?

编辑 - 更新代码

组织

public abstract class Organization
{
    public Organization()
    {
        ChildOrganizations = new HashSet<Organization>();
    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public bool Enabled { get; set; }
    public bool PaymentNode { get; set; }
    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }

    // virtual
    public virtual ICollection<Organization> ChildOrganizations { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

个人

public class Individual : Organization
{
    public string SocialSecurityNumber { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

公司

public class Company : Organization
{
    public string Name { get; set; }
    public string OrganizationNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

的DbContext

public class CoreDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Organization> Organization { get; set; }

    public CoreDbContext(DbContextOptions<CoreDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Man*_*ahi 21

如果有人像我一样犯下愚蠢的错误,我的实体是抽象的。所以也许检查一下你是否错误地提出了同样的问题。

  • OP 提到了这一点,这是一个有意的选择,所以这不是一个“错误”,删除抽象部分也不是解决办法。 (4认同)
  • @EarthMind 有些答案是给其他人的。特别是考虑到这个答案是在问题解决大约四年后发布的。 (2认同)

Joe*_*eth 19

请参阅:https://docs.microsoft.com/en-us/ef/core/modeling/inheritance

如果您不希望为层次结构中的一个或多个实体公开DbSet,则可以使用Fluent API确保它们包含在模型中.

如果您不想DbSet为每个子类创建一个,那么您必须在以下的OnModelCreating覆盖中显式定义它们DbContext:

public class CoreDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Organization> Organization { get; set; }

    public CoreDbContext(DbContextOptions<CoreDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Individual>();
        builder.Entity<Company>();

        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}
Run Code Online (Sandbox Code Playgroud)