How to map Shadow Properties in AutoMapper

Viewed 411

I'm using shadow properties to inject specific properties into many entities by iterating on them in OnModelCreating method.

protected override void OnModelCreating(ModelBuilder builder)
{
    foreach (var entityType in builder.Model.GetEntityTypes())
    {
        // Configure LastModified, ModifiedBy on all entities
        builder.Entity(entityType.Name).Property<DateTimeOffset>("LastModified").HasDefaultValueSql("now()");
        builder.Entity(entityType.Name).Property<string>("ModifiedBy");

        // Configure IsActive on entities with SoftDelete Attribute
        if (Attribute.IsDefined(entityType.ClrType, typeof(SoftDeleteAttribute)))
        {
            builder.Entity(entityType.Name).Property<bool?>("IsActive").HasDefaultValue(true);
        }
    }
}

I'm using AutoMapper to map my entities to DTOs / Models. The problem is it cannot see this dynamically created property in my Entity Class.

I tried MapAtRuntime() method, and tried using the following:

.ForMember(m => m.IsActive, m => m.MapFrom("IsActive"))

However it either doesn't map in the first case, or in the second case would throw an exception that the property is not found on the class.

I tried the solution in the following issue, but it didn't work either! enter link description here

Gives an "Error mapping types." Exception.

Any thoughts would be appreciated.

2 Answers

For shadow properties you can use the following using Automapper:

.ForMember(m => m.IsActive, m => m.MapFrom(src => EF.Property<bool?>(src, "IsActive"))

For those who are looking for this, I've ended up having to create actual public properties on the entities to be able to map them to models.

I'll keep looking, and update this answer if I figured out something.

Related