我正在尝试使用 EF7 迁移,但在为 Organization
建模时卡住了具有继承性的模型。
Organization
是一个抽象类。有两个继承自它的具体类 Individual
和 Company
.
我设置了 Organization
抽象类为 DbSet<Organization>
在DbContext
并运行迁移。
我正在学习本教程 here .
显示以下错误:
The corresponding CLR type for entity type 'Organization' is not instantiable and there is no derived entity type in the model that corresponds to a concrete CLR type.
我该怎么办?
编辑 - 使用代码更新。
组织:
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; }
}
个人
public class Individual : Organization
{
public string SocialSecurityNumber { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
公司
public class Company : Organization
{
public string Name { get; set; }
public string OrganizationNumber { get; set; }
}
数据库上下文
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);
}
}
提前致谢!
最佳答案
请参阅:https://learn.microsoft.com/en-us/ef/core/modeling/inheritance
If you don’t want to expose a DbSet for one or more entities in the hierarchy, you can use the Fluent API to ensure they are included in the model.
如果您不想为每个子类创建一个 DbSet
,那么您必须在 DbContext< 的
:OnModelCreating
重写中显式定义它们
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);
}
}
关于c# - EF7 迁移 - 实体类型 '' 对应的 CLR 类型不可实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37398141/