Is it possible to do something like this:
public abstract class BaseEntity : IEntity
{
private Guid _id;
private DateTime _createdOn;
private DateTime _modifiedOn;
private byte[] _timestamp;
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id => _id;
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime CreatedOn => _createdOn;
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime ModifiedOn => _modifiedOn;
[Timestamp]
public byte[] Timestamp => _timestamp;
}
This is base class, all entities should inherit from this class. Also this properties should be readonly (I'm using backing properties), because EF need to take care of them.
public class Category : BaseEntity
{
[Required]
public string Name { get; set; }
public string Description { get; set; }
}
And OnModelCreating
is empty.
When I run migrations, I get message :
'The entity type 'Project.Database.Models.Category' requires a primary key to be defined.
This seems to be a bug, because it works if you provide public
, internal
or protected
(but not private
or none) setter for the Id
property, or if you specify the key of the derived entity explicitly via Fluent API
modelBuilder.Entity<Category>().HasKey(e => e.Id);
which of course defeats the whole purpose of using the base class property.
You might consider reporting it to EF Core GitHub.