Interface Automapper:接口属性的格式化程序
如果我有一些实现相同接口的类,那么它们都包含相同的属性。有没有办法向这些属性添加格式化程序?我只发现了向特定属性类型添加格式化程序的可能性 下面是一些代码,可以澄清我的意思:Interface Automapper:接口属性的格式化程序,interface,automapper,Interface,Automapper,如果我有一些实现相同接口的类,那么它们都包含相同的属性。有没有办法向这些属性添加格式化程序?我只发现了向特定属性类型添加格式化程序的可能性 下面是一些代码,可以澄清我的意思: public interface ITaggable { IList<string> Tags { get; set; } } public class Post : ITaggable { public IList<string> Tags { get; set; } p
public interface ITaggable
{
IList<string> Tags { get; set; }
}
public class Post : ITaggable
{
public IList<string> Tags { get; set; }
public IList<string> Categories { get; set; }
...
}
public class Page : ITaggable
{
public IList<string> Tags { get; set; }
....
}
但是我想这样做(这段代码不起作用;-)
受保护的覆盖无效配置()
{
ForSourceType()
.ForMember(x=>x.Tags,opt=>opt.AddFormatter());
CreateMap();
CreateMap();
}
这不完全是我所问问题的答案,而是问题的解决方案:
我构建了一个TagsFormatter
,用于检查属性名称中的“标记”:
公共类标记格式化程序:IValueFormatter
{
公共字符串格式值(ResolutionContext上下文)
{
if(context.MemberName.Equals(“Tags”,StringComparison.InvariantCultureIgnoreCase))
{
var tags=context.SourceValue作为IList;
if(标记!=null)
返回字符串。Join(“,”标记);
}
返回context.SourceValue.ToString();
}
}
在配置中,我可以为所有映射注册此格式化程序:
public class ViewModelProfile : AutoMapper.Profile
{
protected override void Configure()
{
ForSourceType<IList<string>>().AddFormatter<TagsFormatter>();
CreateMap<Post, PostViewModel>();
CreateMap<Page, PageViewModel>();
}
}
public类ViewModelProfile:AutoMapper.Profile
{
受保护的覆盖无效配置()
{
ForSourceType().AddFormatter();
CreateMap();
CreateMap();
}
}
试试这个,这是一种完全不同的映射方法,您可以想象一个界面,它仍然可以工作(您可以按照自己的约定),谢谢您的建议。我来看看。
protected override void Configure()
{
CreateMap<Post, PostViewModel>()
.ForMember(x => x.Tags, opt => opt.AddFormatter<TagsFormatter>());
CreateMap<Page, PageViewModel>()
.ForMember(x => x.Tags, opt => opt.AddFormatter<TagsFormatter>());
}
protected override void Configure()
{
ForSourceType<ITaggable>()
.ForMember(x => x.Tags, opt => opt.AddFormatter<TagsFormatter>());
CreateMap<Post, PostViewModel>();
CreateMap<Page, PageViewModel>();
}
public class TagsFormatter : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
if (context.MemberName.Equals("Tags", StringComparison.InvariantCultureIgnoreCase))
{
var tags = context.SourceValue as IList<string>;
if (tags != null)
return String.Join(", ", tags);
}
return context.SourceValue.ToString();
}
}
public class ViewModelProfile : AutoMapper.Profile
{
protected override void Configure()
{
ForSourceType<IList<string>>().AddFormatter<TagsFormatter>();
CreateMap<Post, PostViewModel>();
CreateMap<Page, PageViewModel>();
}
}