简体   繁体   中英

AutoMapper with a complex EF Entity

I have a basic table with a few FK references. So when I retrieve an entity for an update operation; that entity contains ICollections of related entites. I also have a main ViewModel inside which each entity is a sub viewModel. My aim is to use Automapper like:

mapper.Map(MainViewmodel obj,MainEntity obj); 

For this I have a MappingConfiguration like:

 CreateMap<MainViewModel, MainEntity>();
 CreateMap<subViewModel1, subEntity1>();
 CreateMap<subViewModel2, subEntity2>();

This gives me an Unmapped properties exception because the ICollections are not getting mapped. Could anyone please guide me on the best way to deal with this kind of situation?

thanks.

If I understand you correctly, you has classes like this:

class MainViewModel
{
    ICollection<SubViewModel1> SubViewModels { get;set; }
}

class SubViewModel1
{
}

and

class MainEntity
{
    ICollection<SubEntity1> SubEntities { get;set; }
}

class SubEntity1
{    
}

Then you should create rules for each class, and collection of such classes automaper map automatically.

CreateMap<MainViewModel, MainEntity>();
CreateMap<SubViewModel1, SubEntity1>();

Addditions 1:

  1. Try this method: var mappedMainEntity = rmapper.Map<MainEntity>(MainViewmodel obj);
  2. If you map MainEntity to MainViewModel you need add .ReverseMap() to map rule, like this:

    CreateMap().ReverseMap(); CreateMap().ReverseMap();

Additions 2:

  1. AutoMapper mapping public Properties only
  2. If the mapping Properties have different names, you need to use explicitly indicating how to map these Properties. Using ForMember method and MapFrom option. Example

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