Reputation: 870
I have a model and ViewModel like this
public class Estate : BaseEntity
{
public virtual BaseInformation floorType { get; set; }
}
public class BaseInformation:BaseEntity
{
public string Name { get; set; }
public virtual BaseInformationHeader Master { get; set; }
}
public class EstateViewModel : BaseEntityViewModel
{
public long floorType { get; set; }
}
And the code in controller:
[HttpPost]
public long save(EstateViewModel estateViewModel)
{
Estate entity = new Estate();
BaseInformation bi = new BaseInformation();
bi.id = 1;
entity.floorType = bi;
EstateViewModel ev = new EstateViewModel();
Mapper.CreateMap<EstateViewModel, Estate>();
var model = AutoMapper.Mapper.Map<EstateViewModel,Estate>(estateViewModel);
return estateRepository.save(entity);
}
When the action is executed AutoMapper throws the following exception:
An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code
What is causing this to happen?
Upvotes: 2
Views: 2350
Reputation: 870
my problem solution found here : http://cpratt.co/using-automapper-creating-mappings/ and the code is like this:
AutoMapper.Mapper.CreateMap<PersonDTO, Person>()
.ForMember(dest => dest.Address,
opts => opts.MapFrom(
src => new Address
{
Street = src.Street,
City = src.City,
State = src.State,
ZipCode = src.ZipCode
}));
Upvotes: 2
Reputation:
Check out the inner exception - it gives you a good description of the problem. I would also consider setting up all of the CreateMap calls in a static method somewhere else that is called on app start:
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.CreateMap<EstateViewModel, Estate>();
}
}
And then in Global.asax:
protected void Application_Start()
{
AutoMapperConfiguration.Configure();
}
[Update] - to map properties to other properties with different names:
Mapper.CreateMap<ViewModel, Model>()
.ForMember(dest => dest.Id, o => o.MapFrom(src => src.DestinationProp));
The problem you have is that the source property is a long
while the destination is a complex type - you can't map from the source to the destination as they are not the same type.
[Update 2]
If BaseInformation.Id is a long then you shoiuld be able to do this:
Mapper.CreateMap<ViewModel, Model>()
.ForMember(dest => dest.Id, o => o.MapFrom(src => src.floorType ));
You're model isn't very clear though.
Upvotes: 0