Search code examples
c#asp.net-mvcentity-framework-6automapper-6

Mapping viewModel object to ICollection 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. My main viewModel contains Lists which correspond to these ICollections. However, since some other models represent 1-1 mapping, I have object instead of List. But inside the Entity they continue to be represented as ICollections.

This is giving me some problems when trying to map between viewModel and Entity. I am using Automapper for the mapping. I have

mapper.Map(viewModel, entity); 

Currently I am leaving out the problematic models from this mapping and adding them separately. Is there a way to handle everything in one mapping? Is there a way to deal with the ICollections which ideally should be a single object?

EDIT

public class MainViewModel
{
        public EntityVM1 vm1 { get; set; }        
        public List<EntityVM2> vm2 { get; set; }        
        public List<EntityVM3> vm3 { get; set; }    
}  

public class MainEntity
{
  ... some scalar props...

public virtual ICollection<Entity1> e1 { get; set; }        
public virtual ICollection<Entity2> e2 { get; set; }        
public virtual ICollection<Entity3> e3 { get; set; }        

}

Entity1 and EntityVM1 are causing the problem.

Thanks


Solution

  • You can always override the default mapping system in the mapping config of AutoMapper, you should have a peek at the runtime polymorphism in the mapping inheritance section of the documentation.

    If what you want on the entity is a straight object, why not take Automapper out of the equation and just force EF to map it using a one to one system... i.e

    modelBuilder.Entity<MainEntity>()
            .HasOne(p => p.Entity1)
            .WithOne(i => i.MainEntity)
            .HasForeignKey<Entity1>(b => b.MainEntityForignKey);
    

    HAve a peek at the EF docs, under section one-to-one for more info