1

I'm facing an issue with casting in AutoMapper. Following are details.

Here is my source class

public class FamilyModel
{
    public int FamilyID { get; set; }
    public string FamilyName { get; set; }
}

And here is my destination class

public class SaveKitViewModel
{
    public int FamilyID { get; set; }
    public string FamilyName { get; set; }
    public int UserId { get; set; }
}

Now when i'm trying to caste source object to destination object using Automapper it gives me error and I'm trying to ignore UserId object coz it's not present in Source class

var mapper = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<FamilyModel, SaveKitViewModel>()
        .ForMember(d => d.UserId, m => m.Ignore());
    }).CreateMapper();
   dbObject = mapper.Map(model, dbObject);
}

Can any one please tell me what's wrong with above code?

StuartLC
  • 104,537
  • 17
  • 209
  • 285
Hetal
  • 631
  • 1
  • 7
  • 19
  • I'm getting following error @JamesDev Missing type map configuration or unsupported mapping – Hetal Apr 01 '16 at 12:52

2 Answers2

1

Since UserId isn't in the source map, you don't need to explicitly .Ignore it in the mapping bootstrapping - it will be ignored by default.

Seemingly you want to merge the mapped source properties into an existing destination object. You won't need to reassign the destination object - the existing properties will be mutated. For example:

var mapper = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<FamilyModel, SaveKitViewModel>();
}).CreateMapper();

var existingSaveKitViewModel = new SaveKitViewModel
{
    UserId = 1234
};
var familyModel = new FamilyModel
{
    FamilyID = 9876,
    FamilyName = "Bloggs"
};
mapper.Map(familyModel, existingSaveKitViewModel);

Results in a merged existingSaveKitViewModel:

    FamilyID = 9876,
    FamilyName = "Bloggs"
    UserId = 1234
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • @HetalJariwala My example works as listed above - I've added it to [GitHub here](https://github.com/nonnb/SO36353982/blob/master/ConsoleApplication1/Program.cs). Perhaps your MVCE isn't a true representation of the issue. Please edit your original question with the actual issue? – StuartLC Apr 05 '16 at 06:47
0

Try this:

Mapper.Initialize(cfg => {
   cfg.CreateMap<FamilyModel, SaveKitViewModel>();
});

SaveKitViewModel sktv = new SaveKitViewModel();
FamilyModel fm = Mapper.Map<FamilyModel>(sktv.OfType<SaveKitViewModel>());
koryakinp
  • 3,989
  • 6
  • 26
  • 56