如何根据MaxLength属性使AutoMapper截断字符串? [英] How to make AutoMapper truncate strings according to MaxLength attribute?
问题描述
我有一个要映射到实体的DTO.该实体具有一些用MaxLength
属性修饰的属性.
I have a DTO I want to map to an entity. The entity has some properties decorated with the MaxLength
attribute.
我希望AutoMapper在根据每个属性的MaxLength
映射到我的实体时截断来自DTO的所有字符串,这样在保存实体时不会出现验证错误.
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; }
}
我希望这样做:
var myDto = new MyDto() { Name = "1231321312312312312312" };
var entity = Mapper.Map<Entity>(myDto);
生成的entity
的Name
不得超过10个字符.
The resulting entity
should have its Name
limited to a maximum of 10 characters.
推荐答案
我不确定放置该逻辑的好地方,但这是一个适合您的情况的示例(AutoMapper 4.x): 使用AutoMapper自定义映射
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
在此示例中,我正在读取实体上的自定义MapTo
属性,您可以使用MaxLength
进行相同操作.
In this example, I'm reading a custom MapTo
property on my entity, you could do the same with MaxLength
.
这里是当前版本的AutoMapper(6.x)的完整示例
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; }
}
这篇关于如何根据MaxLength属性使AutoMapper截断字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!