I have requirement to create composite key in Entity Framework.
My base class key is "Guid" and there is something unique I want in student class like "ID" which can be readable. like "STUD01", which really requires readable unique data.
[NotMapped]
public class BaseEntity
{
public Guid Key { get; set; }
public DateTime? DateCreated { get; set; }
public string UserCreated { get; set; }
public DateTime? DateModified { get; set; }
public string UserModified { get; set; }
}
Here is my Student
class
public class Student : BaseEntity
{
public string Id { get; set; }
public string Name { get; set; }
}
Here is my context class
public class SchoolContext: DbContext
{
public LibraContext(DbContextOptions<SchoolContext> options)
: base(options)
{ }
public DbSet<Student> Students { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BaseEntity>().Property(x => x.DateCreated).HasDefaultValueSql("GETDATE()");
modelBuilder.Entity<BaseEntity>().Property(x => x.DateModified).HasDefaultValueSql("GETDATE()");
//here is my composite key
modelBuilder.Entity<Student>().HasKey(c => new { c.Key, c.Id });
}
I have run the below migration commands to create script and update database
Add-Migration -Name "InitialMigration" -Context "SchoolContext"
and I get this error:
A key cannot be configured on 'Student' because it is a derived type. The key must be configured on the root type 'BaseClass'. If you did not intend for 'BaseClass' to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model.
How to achieve it?
I am using ASP.NET Core 2.1