EF Core base entity class inheritance and readonly properties

.net-core asp.net-core c# entity-framework entity-framework-core

Question

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.

1
0
10/9/2016 1:32:27 PM

Popular Answer

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.

2
10/9/2016 3:23:54 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow