我尝试使用EF7迁移,并在使用继承建模组织模型时遇到困难。
组织是一个抽象类,有两个继承它的具体类叫做Individual and Company。
我在DbContext中将组织抽象类设置为DbSet并运行迁移。
我遵循本教程here
显示以下错误:
实体类型的相应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; }
}
个人
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; }
}
的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);
}
}
提前致谢!
答案 0 :(得分:19)
请参阅:https://docs.microsoft.com/en-us/ef/core/modeling/inheritance
如果您不想为层次结构中的一个或多个实体公开DbSet,可以使用Fluent API确保它们包含在模型中。
如果您不想为每个子类创建DbSet
,则必须在OnModelCreating
的{{1}}覆盖中明确定义它们:
DbContext
答案 1 :(得分:1)
与您关联的教程类似,您的DbSet<>
属性应该是继承的Individual
和Company
类。
尝试让CoreDbContext
看起来更像这样:
public class CoreDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Company> Companies { get; set; }
public DbSet<Individual> Individuals { 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);
}
}
答案 2 :(得分:0)
问题可能是您使用class library
项目。在EF Core的RC2中,您无法将DBContext放在这样的项目中。这是一个已知的问题。当您将其转换为“app”项目时,它应该再次工作。
更多信息&amp;源:强>
解决方法:https://docs.efproject.net/en/latest/cli/dotnet.html#dotnet-cli-issues
Github问题: https://github.com/aspnet/EntityFramework/issues/5460
答案 3 :(得分:0)
万一有人犯了像我这样的愚蠢错误,我的实体就是抽象的。所以也许检查一下您是否犯了同样的问题。
答案 4 :(得分:0)
您还应该在 CoreDbContext
类中放置继承 Organization 的类。然后它将正确区分和实例化这些对象。它应该是这样的:
public DbSet<Organization> Organization { get; set; }
public DbSet<Individual> Individual { get; set; }
public DbSet<Company> Company { get; set; }
来源:https://docs.microsoft.com/en-us/ef/core/modeling/inheritance