[英]Using Automapper with Flags Enum
I'm trying to figure out how to use AutoMapper with the following scenario :- 我试图找出如何在以下情况下使用AutoMapper:-
I have the following Entity Model :- 我有以下实体模型:
public class Lender : LegacyEntity
{
public int Id { get; set; }
public string Name { get; set; }
public ClaimType ClaimTypes { get; set; }
//Other properties kepy out for brevity.
}
And Here is The Following Service Model :- 以下是以下服务模型:-
public class LenderServiceModel
{
[Editable(false)]
public int Id { get; set; }
[Editable(false)]
public string Name { get; set; }
[Editable(false)]
public List<string> ClaimTypes { get; set; }
}
In the case of the Entity model, the ClaimType property is a Flags Enum :- 在实体模型的情况下,ClaimType属性是一个Flags Enum:
[Flags]
public enum ClaimType : int
{
A = 1,
B = 2,
C = 4,
}
I want to be able to map from the Entity Model, to the Service Model. 我希望能够从实体模型映射到服务模型。 I need to map the ClaimType to List on the Service Model, but i have had no luck.
我需要将ClaimType映射到服务模型上的List,但是我没有运气。
I'm new to AutoMapper, any help would be apreciated. 我是AutoMapper的新手,对您的帮助将不胜感激。
First you need to get hold of a string list representation of your enum flags, this can be done with this statement 首先,您需要掌握枚举标志的字符串列表表示形式,这可以通过以下语句完成
var t = Enum.GetValues(typeof(ClaimType)).Cast<ClaimType>().Where(r => (claimType & r) == r).Select(r => r.ToString()).ToList();
For specific mappings with AutoMapper you need to specify it while setting it up. 对于使用AutoMapper的特定映射,您需要在设置时指定它。 So for this that will be following code: so we map ClaimTypes field from source to destination using the list conversion...
因此,这将是以下代码:因此,我们使用列表转换将ClaimTypes字段从源映射到目标...
AutoMapper.Mapper.CreateMap<LegacyEntity, LenderServiceModel >()
.ForMember(dest => dest.ClaimTypes,
opts => opts.MapFrom(Enum.GetValues(typeof(ClaimType)).Cast<ClaimType>().Where(r => (src.ClaimTypes & r) == r).Select(r => r.ToString()).ToList());
You need to create a property mapping for ClaimTypes, which converts each flags value to a string. 您需要为ClaimTypes创建一个属性映射,该映射将每个标志值转换为字符串。 There are a few ways to do this.
有几种方法可以做到这一点。 Take a look at this answer for some ideas.
看看这个答案的一些想法。
Here's how you can set it up in AutoMapper (using a quick and dirty method of just ToString()
ing the enum then splitting the string): 这是在AutoMapper中进行设置的方法(使用仅
ToString()
枚举枚举然后拆分字符串的快速而肮脏的方法):
Mapper.CreateMap<Lender, LenderServiceModel>()
.ForMember(dest => dest.ClaimTypes, opts => opts.MapFrom(src =>
src.ClaimTypes.ToString().Split(new string[]{", "}, StringSplitOptions.None).ToList()));
You can see a working .NETFiddle here 您可以在这里看到正常的.NETFiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.