Reputation: 4892
In my domain model I'm trying to setup mappings for common properties only for entities that are subclass of EntityBase. For this purpose I'm trying to filter out using IsAssignableFrom but it is giving no results and not mapping happens for those properties.
Any advice on how to resolve the IsAssignableFrom issue, or any other way to verify entity hierarchy will be appreciated.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var types = modelBuilder.Model.GetEntityTypes().Where( entity =>
typeof(Domain.Core.Entity).IsAssignableFrom(entity.GetType()));
foreach (var entType in types)
{
entType.AddProperty("CreatedBy", typeof (string));
entType.AddProperty("ModifiedBy", typeof(string));
entType.AddProperty("CreatedOn", typeof(DateTime));
entType.AddProperty("LastModifiedOn", typeof(DateTime));
entType.AddProperty("RowVersion", typeof(byte[]));
}
}
Upvotes: 0
Views: 741
Reputation: 37
Your on the right track, but I'd recommend that you should get your entity types using pure reflection rather than through the model. Try something like this:
var asm = Assembly.Load("Domain.Core");
foreach(var type in asm.GetTypes())
{
if(typeof(Domain.Core.Entity).IsAssignableFrom(type))
{
var builder = modelBuilder.Entity(type);
builder.Property(typeof(string), "CreatedBy");
// ...
}
}
Upvotes: 0
Reputation: 23098
I think IsAssignableFrom is not used correctly in your case:
typeof(Domain.Core.EntityBase).IsAssignableFrom(entity.GetType())
should be used if your intention is to iterate through all types that derive (directly on indirectly) from EntityBase
Upvotes: 1