我正在使用 AutoMapper 以通常的方式映射 POCO。但我有一个常见的场景,我想映射一个类,例如:
class MyClassSrc
{
public int my_property {get; set;}
}
class MyClassDest
{
public int MyProperty {get; set;}
}
但我认为我需要比以下提供的更多的灵活性:
cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
因为目标对象可能会也可能不会被干净地调用
MyProperty
。例如,我通常可能想要这种格式,但可能还有另一种情况,我希望它是 Acronym_XYZ
或 _3D_Game
,我保留下划线以使其更具可读性,或者因为 .net 标识符不能以数字开头。
我也一直想要不区分大小写的映射。
内置的命名约定是否会简单地忽略所有下划线,并保持区分大小写,将
my_property
正确映射到My_Property
,还是我需要为此自定义约定? (如果是这样,您如何构建一个在这种模糊意义上比较源属性名称和目标属性名称的模型)?
停止使用映射器,使用接口,并通过所述接口编写您自己的映射,如本例所示。
没有理由尝试采用框架方法来解决这个问题,因为它有一个字面上的解决方案,如果您自己正确编写它,则更容易维护。如果您尝试使用框架,您不会节省太多时间,可能只会损失更多时间。
就像这个例子:
using System;
using System.Collections.Generic;
namespace StackOverFlowAntiMapper
{
public class Program
{
public static void Main(string[] args)
{
Book source = new Book()
{
genre = "Horror",
Pages = 200,
Title = "Scary Book"
};
BookDto bookDto = new BookDto(source);
Console.WriteLine("Name: " +bookDto.Name);
Console.WriteLine("PageCount: " +bookDto.PageCount);
}
}
public class BookDto
{
public string Name { get; set; }
public int PageCount { get; set; }
public GenreDto Genre { get; set; }
public BookDto(IMapToBookDto source) {
Name = source.GetName();
PageCount = source.GetPageCount();
Genre = source.GetGenre();
}
}
public class GenreDto {
public string Tag { get; set; }
public List<Genre> GenreList { get; set; }
public GenreDto(IMapToGenreDto source)
{
Tag = source.GetTagValue();
GenreList = source.GetGenreList();
}
}
public interface IMapToBookDto
{
GenreDto GetGenre();
string GetName();
int GetPageCount();
}
public interface IMapToGenreDto
{
List<Genre> GetGenreList();
string GetTagValue();
}
public class Book : IMapToBookDto
{
public string Title { get; set; }
public int Pages { get; set; }
public string genre { get; set; }
public GenreDto GetGenre()
{
return new GenreDto(new GenreDtoMapper(genre));
}
public string GetName()
{
return Title;
}
public int GetPageCount()
{
return Pages;
}
}
public class GenreDtoMapper : IMapToGenreDto
{
public string _genre;
public GenreDtoMapper(string genre)
{
_genre = genre;
}
public List<Genre> GetGenreList()
{
List<Genre> result = new List<Genre>();
Genre genreFround = (Genre)Enum.Parse(typeof(Genre), _genre);
result.Add(genreFround);
return result;
}
public string GetTagValue()
{
return _genre;
}
}
public enum Genre
{
Horror,
Comedy,
Fantasy,
Tragedy,
Documentary
}
}
停止使用地图框架!!!使用接口并实现“不稳定”的特定映射。
这将为您节省大量时间,如果您使用可靠且干净的代码以及依赖注入,您将拥有如此干净的映射器,任何可以阅读 C# 的人不仅会理解映射是如何工作的,他们还能够如果您的系统发生变化,请扩展您的映射器。
映射框架是良好代码的反模式,并表明您是一个糟糕的程序员。使用它们对代码库的贡献会更差。