'The corresponding CLR type for entity type 'Employee' is not instantiable
My error:
The corresponding CLR type for entity type 'Employee' is not instantiable and there is no derived entity type in the model that corresponds to a concrete CLR type
I'm trying to use migration in EF Core. I'm using a Code-First approach.
I have one abstract class named Employee
which has properties like Id
, Name
, UserId
.
My requirement is to specify whether an Employee
is Contract
or Permanent
.
My code is as follows:
public abstract class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
}
My concrete class:
public class Contract : Employee
{
// Left empty because I don't want to add any other columns
}
public class Permanent : Employee
{
// Left empty because I don't want to add any other columns
}
and my DbContext:
public class CoreDbContext : IdentityDbContext<ApplicationUser>
{
public CoreDbContext(DbContextOptions<CoreDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Contract>();
builder.Entity<Permanent>();
base.OnModelCreating(builder);
}
}
Correct me where I am wrong.
Solution 1:[1]
You will need to define a mapping of class Employee
to a table, like this:
builder.Entity<Employee>().ToTable("Employee");
This uses the Table Per Class Hierarchy/Single Table Hierarchy mapping model, which uses a column as the discriminator between the different types that are stored on the same table.
Solution 2:[2]
Remove "abstract" from class definition. I don't know why it is like that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ricardo Peres |
Solution 2 |