I have a BaseClass that is abstract and has many abstract properties.
I have a dozen or so (they probably grow) entities that are part of the Entity Framework, each of which is derived from BaseClass.
I try to avoid the need:
modelBuilder.Entity<Entity1>().HasKey(t => t.Id);
modelBuilder.Entity<Entity2>().HasKey(t => t.Id);
modelBuilder.Entity<Entity3>().HasKey(t => t.Id);
...
for each property and each object, as this seems very wasteful and creates a lot of code duplication. I experimented with getting all Entities in the namespace that come from BaseClass:
var derivedEntities = Assembly.GetExecutingAssembly().GetTypes().
Where(t => t.Namespace == "My.Entities" && t.IsAssignableFrom(typeof(BaseClass)));
However, the following logical steps:
foreach (var entity in derivedEntities)
{
modelBuilder.Entity<entity>().HasKey(t => t.Id);
}
but will not compile because
"entity is a variable, but used as a type."