E-Bat
E-Bat

Reputation: 4892

Mapping Common Properties only once for the whole Model in Entity Framework 7

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

Answers (2)

JeffGillin
JeffGillin

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

Alexei - check Codidact
Alexei - check Codidact

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

Related Questions