[英]Naming conventions in AutoMapper when unflattening foreign key
I've just started looking at AutoMapper and wish to change one specific behaviour. 我刚刚开始研究AutoMapper,希望更改一种特定的行为。
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. 下面的代码可以正常工作,但是我更希望在DeviceTemperatureEntryViewModel DeviceId中命名Guid而不是在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.
如果我将其命名为DeviceId,则展开将正常进行,从而导致设备类型的ID设置正确,但不会调用自定义转换器。
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的映射之间做出决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.