简体   繁体   中英

Configuring AutoMapper Maps for Dynamic/Expando Object

I'm using AutoMapper to map ExpandoObjects to an Entity and want to configure some rules for the mappings, specifically, I don't want to map to any property that inherits from Entity; I tried to set Ignore on those properties, but it never executes for the top level object, I hit the break point for the properties of the Entity that inherit from Entity string => Entity, but never for ExpandoObject => Entity.

Startup.cs

public IServiceProvider ConfigureServices(IServiceCollection services)
{
  services.AddAutoMapper(config =>
  {
    config.ForAllMaps((cfg, expr) =>
    {
      if (typeof(Entity).IsAssignableFrom(cfg.DestinationType))
      {
        var properties = cfg.DestinationType.GetProperties()
            .Where(prop => typeof(Entity).IsAssignableFrom(prop.PropertyType));

        foreach (var prop in properties)
        {
          expr.ForMember(prop.Name, opt => opt.Ignore());
        }
      }
    });

    config.CreateMissingTypeMaps = true;
    config.ValidateInlineMaps = false;
  });

I found some code that works, but I was hoping to find a way to do it that wasn't global.

.AddAutoMapper(config =>
{
  config.ShouldMapProperty = pi => !typeof(Entity).IsAssignableFrom(pi.PropertyType);

  config.CreateMissingTypeMaps = true;
  config.ValidateInlineMaps = false;
});

Is there a way to configure maps for ExpandoObjects? The documentation shows how to map them, but it doesn't have any information on configuring the maps for them...

No, mapping from ExpandoObject is built in and doesn't work like a regular map you create yourself. And there is no way to configure it. Here is the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM