I've just started looking at AutoMapper and wish to change one specific behaviour.
I have a simple view model that contains a foreign key which I want to convert using a custom converter. My problem however is that I cannot get it to work unless I name the property in the view model the same as the type name.
The following code works correctly, but I would rather name the Guid in DeviceTemperatureEntryViewModel DeviceId instead of only Device. If I name it DeviceId the unflattening works, resulting in a Device type with the Id set correctly, but the custom converter is not invoked.
public MappingProfile()
{
CreateMap<Device, DeviceViewModel>().ReverseMap();
CreateMap<DeviceTemperatureEntry, DeviceTemperatureEntryViewModel>().ReverseMap();
// Lookups
CreateMap<Guid, Device>().ConvertUsing<EntityConverter<Device>>();
}
public class EntityConverter<T> : ITypeConverter<Guid, T> where T : class
{
private readonly ApplicationDbContext _context;
public EntityConverter(ApplicationDbContext context)
{
_context = context;
}
public T Convert(Guid source, T destination, ResolutionContext context)
{
return _context.Find<T>(source);// default(T);
}
}
public class DeviceTemperatureEntryViewModel
{
public Guid Id { get; set; }
public Guid Device { get; set; }
public double Temperature { get; set; }
}
public class DeviceTemperatureEntry : DeviceEntry
{
public double Temperature { get; set; }
}
public class DeviceEntry
{
[Key]
public Guid Id { get; set; }
[Required]
public DateTime Timestamp { get; set; }
public Device Device { get; set; }
public DeviceEntry()
{
Timestamp = DateTime.Now;
}
}
您必须在展开和从Guid到Device的映射之间做出决定。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.