[英]Generic AutoMapper Mapping for all inheriting from a specific class
The majority of my view models inherit from a base view model called EncryptedBaseViewModel
. 我的大多数视图模型都继承自称为
EncryptedBaseViewModel
的基本视图模型。 This method encrypts the ID so the user does not see database sensitive information. 此方法对ID进行加密,因此用户看不到数据库敏感信息。
I would like to create an AutoMapper mapping that handles all mappings between any entity that maps to the EncryptedBaseViewModel
. 我想创建一个AutoMapper映射,以处理映射到
EncryptedBaseViewModel
任何实体之间的所有映射。 Get the source ID value and pass it to the destinations SetId method. 获取源ID值,并将其传递给目标SetId方法。
The ViewModel Class ViewModel类
class EncryptedBaseViewModel
{
private string _encryptedId;
public int Id {get; set; } // to be after new mapping method is developed.
public void SetId(int id)
{
_encryptedId = Encrypted(id);
}
public string GetId()
{
return _encryptedId;
}
}
Auto Mapper Example 自动映射器示例
I have
forged
hacked this example, which passes the value after mapping as not sure of the approach. 我
伪造了
这个示例,该示例在映射后传递了值(不确定方法)。 Suggestions welcome here. 欢迎在这里提出建议。
CreateMap<AnySource, EncryptedBaseViewModel>().ForMember(vm => nameof(vm.Id), opt => opt.Ignore()).AfterMap((src,dest) => dest.SetId(src.Id));
The Questions 问题
AnySource
is specified? AnySource
在指定AnySource
地方AnySource
什么? I'm trying to avoid having to write the same mapping for every entity, as this could lead to situations where one forgets to do it. 我试图避免为每个实体编写相同的映射,因为这可能会导致人们忘记这样做的情况。
As @DavidG said, you need a base class or interface for your source. 如@DavidG所说,您的源需要一个基类或接口。 You can also map from object, but that is not terribly useful, because you still need to access the source id somehow.
您也可以从对象映射,但这并不是非常有用,因为您仍然需要以某种方式访问源ID。 And why the AfterMap?
为什么使用AfterMap? That's a hack.
那是骇客。 You can write a resolver inline or a resolver class.
您可以编写内联的解析器或解析器类。 And about your second point, you need Include if you want both mappings to run (base and derived).
关于第二点,如果要同时运行两个映射(基础映射和派生映射),则需要包含。 The docs .
的文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.