0

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

Shwrk
  • 173
  • 1
  • 11

1 Answers1

0

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

John Mitchell
  • 9,653
  • 9
  • 57
  • 91
  • Hi @JohnMitchell , thanks for the reply. In my case either I have to make the viewModel a list or convert it into a list inside the mapping config. But ideally I want the Entity to be regular object instead of ICollection, so that the mapping reflects the relationship. Is there a way to do that? – Shwrk Jan 02 '18 at 11:30
  • If what you want on the entity is a straight object, why not take Automapper out of the equation (See edit above) – John Mitchell Jan 02 '18 at 11:37
  • Its definitely something that should be fixed at Entity level rather than by Automapper. I'll try changing some constraints on the tables. ( using DB first) Thanks for pointing me in the right direction ;) – Shwrk Jan 02 '18 at 11:51