简体   繁体   English

使用AutoMapper映射静态类

[英]Map static classes with AutoMapper

Is there a way to map static classes with AutoMapper? 有没有办法用AutoMapper映射静态类?

Scenario is like this. 场景是这样的。 There is a static class called UserIdentity and it contains properties. 有一个称为UserIdentity的静态类,它包含属性。 I want to map UserIdentity class values to my none static class called UserDTO . 我想将UserIdentity类的值映射到名为UserDTO静态类。

When I tried 当我尝试

AutoMapper.Mapper.CreateMap<UserIdentity, UserDTO>();

There is an error saying, 有一个错误的说法,

static type cannot be used as type arguments

Now can anyone explain me about this scenario and is it achievable or not. 现在任何人都可以向我解释这种情况,这是否可以实现。 And is there a way to map static classes without using Automapper. 有没有一种方法可以映射静态类而不使用Automapper。 Otherwise I have to do them manually. 否则,我必须手动进行操作。

The only way to do this would be to use a dummy class to perform a no-op mapping. 唯一的方法是使用伪类执行无操作映射。 Then you could use a custom type converter, or mapping function or simply do something like this: 然后,您可以使用自定义类型转换器或映射函数,也可以简单地执行以下操作:

Mapper.CreateMap<Dummy, Dest>()
  .AfterMap((src, dest) => 
     { 
         dest.Name = UserIdentity.Name;
         dest.Id = UserIdentity.Id;
         //.... etc..
     });

Unfortunately you cant use automapper on static classes 不幸的是,您不能在静态类上使用automapper

Additionally there are a very limited set of situations in which you can refer to static class types, which will also make other approaches difficult 此外,在少数情况下,您可以引用静态类类型,这也会使其他方法变得困难

Static classes prevent inappropriate use, so in almost all situations, you can't use them in situations where you'd normally want an instance of the type... and that includes type arguments. 静态类可以防止不当使用,因此在几乎所有情况下,您都不能在通常需要type ...实例(包括type参数)的情况下使用它们。

The only way i can see to achieve your desired results is to create a field by field mapping function your self 我能看到的达到您期望结果的唯一方法是通过自己的字段映射功能创建一个字段

All though you can force automapper to use a dummy class, you are still mapping field by field anyway, my vote is to reduce complexity and just use something like the following 尽管您可以强制automapper使用虚拟类,但无论如何您仍在逐字段进行映射,我的投票是降低复杂性,仅使用以下内容

  public static SomeDTO CreateDTO()
  {
     return new SomeDTO
        {
            dest.Name = UserIdentity.Name;
            dest.Id = UserIdentity.Id;
            ect..
        }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM