How to make AutoMapper truncate strings according to MaxLength attribute?
I'm not sure that it's a good place to put that logic, but here is an example that should work in your case (AutoMapper 4.x): Custom Mapping with AutoMapper
In this example, I'm reading a custom MapTo
property on my entity, you could do the same with MaxLength
.
Here a full example with the current version of AutoMapper (6.x)
class Program
{
static void Main(string[] args)
{
Mapper.Initialize(configuration =>
configuration.CreateMap<Dto, Entity>()
.ForMember(x => x.Name, e => e.ResolveUsing((dto, entity, value, context) =>
{
var result = entity.GetType().GetProperty(nameof(Entity.Name)).GetCustomAttribute<MaxLengthAttribute>();
return dto.MyName.Substring(0, result.Length);
})));
var myDto = new Dto { MyName = "asadasdfasfdaasfasdfaasfasfd12" };
var myEntity = Mapper.Map<Dto, Entity>(myDto);
}
}
public class Entity
{
[MaxLength(10)]
public string Name { get; set; }
}
public class Dto
{
public string MyName { get; set; }
}