Iskander Raimbayev Iskander Raimbayev - 2 months ago 6
C# Question

Entity Framework : Is it possible to inherit from base configuration class?

I am modeling a new database by EF CodeFirst. Here I have an abstract base class and every domain model inherited from this class:

public abstract class Entity
{
public Guid Id { get; set; }
public byte [] TimeStamp { get; set; }
}


And there a lot of classes like :

public class Country : Entity
{
public string Name { get; set; }
public string InternationalCode { get; set; }
public Location Location { get; set; }
public ICollection<City> Cities { get; set; }

public Country(string name, string internationalCode, decimal latitude, decimal longitude)
: this(name, internationalCode)
{
Location.Latitude = latitude;
Location.Longitude = longitude;
}
public Country(string name, string internationalCode) : this()
{
Name = name;
InternationalCode = internationalCode;
}

public Country()
{
Location = new Location();
Cities = new List<City>();
}
}


And every model's configuration based on FluentAPI :

public CountryConfiguration()
{
HasKey(p => p.Id);
Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.TimeStamp).IsRowVersion();

Property(p => p.Name).IsRequired().HasMaxLength(100);
Property(p => p.InternationalCode).IsRequired().HasMaxLength(5);

HasMany(p => p.Cities)
.WithOptional(p => p.BelongedCountry)
.HasForeignKey(p => p.BelongedCountryId);
}


The problem is that

HasKey(p => p.Id);
Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.TimeStamp).IsRowVersion();


this piece copy-pasted more than 30+ times for each domain model. Is there any way to make Configuration classes inherit from EntityTypeConfiguration but also inherit\contain configuration from Entity Configuration?

public class EntityConfiguration : EntityTypeConfiguration<Entity>
{
public EntityConfiguration()
{
HasKey(p => p.Id);
Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.TimeStamp).IsRowVersion();
}
}


I know, that C# doesn't allow multiple inheritance. What can you suggest?

Answer

Unless I'm missing something, can't you use an abstract class?

public abstract class BaseEntityConfiguration<T> : EntityTypeConfiguration<T> where T : Entity 
{
  protected BaseEntityConfiguration()
  {
      HasKey(p => p.Id);
      Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
      Property(p => p.TimeStamp).IsRowVersion();
  }
}

public class CountryConfiguration : BaseEntityConfiguration<Country>
{}
Comments