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?
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