I have a DTO I want to map to an entity. The entity has some properties decorated with the MaxLength
attribute.
I would like AutoMapper to truncate all the strings coming from the DTO when mapping to my entity according to the MaxLength
for each property, so that I don't get validation errors when saving the entity.
So, if entity is defined like this:
public class Entity
{
[MaxLength(10)]
string Name { get; set; }
}
I would like that doing this:
var myDto = new MyDto() { Name = "1231321312312312312312" };
var entity = Mapper.Map<Entity>(myDto);
The resulting entity
should have its Name
limited to a maximum of 10 characters.
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With