简体   繁体   中英

AutoMapper ignores MaxDepth when foreign key entity is of the same type

I am trying to get AutoMapper to only map the first level of an Entity, so I set MaxDepth(1), which works great, except for my Menu entity which has a property called ParentMenu that is also of type Menu.

Startup.cs

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services
      ...
      ...
      .AddAutoMapper(config =>
      {
        config.AddProfiles(typeof(Startup).Assembly);
        config.ForAllMaps((cfg, expr) =>
        {
           if (typeof(Entity).IsAssignableFrom(cfg.DestinationType))
           {
              expr.MaxDepth(1);
           }
        });
        config.CreateMissingTypeMaps = true;
        config.ValidateInlineMaps = false;
      });
   ...
   ...
}

Menu.cs

public class Menu : Entity
{
  int Id {get; set;}
  string Name {get; set;}
  int ParentMenuId {get; set;}
  Menu ParentMenu {get; set;}
  int ModuleId {get; set;}
  Module Module {get; set;}
}

MenuViewModel.cs

public class MenuViewModel
{
  int Id {get; set;}
  string Name {get; set;}
  int ParentMenuId {get; set;}
  string ParentMenuName {get; set;}
  int ModuleId {get; set;}
  string ModuleName {get; set;}
}

MenuController.cs

public IActionResult Edit(MenuViewModel viewModel)
{
  var model = EditGetModel(id); // returns the Menu Entity
  Mapper.Map(viewModel, model);
  // model.ParentMenuId is set properly
  // model.ParentMenu set to a new instance of Menu ignoring MaxDepth(1)
  // model.ModuleId is set properly
  // model.Module is properly left null
  ...
  ...
}

I can't figure out why MaxDepth(1) is ignored when an Entity has a property of the same type, any help would be greatly appreciated.

This doesn't seem to have anything to do with depth or recursion. It's also not clear what the exact problem is. The code you have is mapping a view model onto an entity. If I had to guess, I'd imagine the issue is that AutoMapper is creating a new Menu instance and replacing the existing ParentMenu property on your entity with that. The reason is that you're projecting ParentMenuName , which will map to ParentMenu.Name on the entity. You should ignore ParentMenu in the mapping:

CreateMap<MenuViewModel, Menu>()
    ...
    .ForMember(dest => dest.ParentMenu, opts => opts.Ignore());

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