简体   繁体   English

AutoMapper忽略扩展方法

[英]AutoMapper ignoring extension method

I have 2 models: 我有2个型号:

User.cs: User.cs:

  • Firstname 名字
  • Lastname
  • Email 电子邮件
  • Password 密码

Authentication.cs Authentication.cs

  • Email 电子邮件
  • Password 密码

I would like the Email and Password from the Authentication model to map to the Email and Password within the User model so in my MappingProfile I have: 我希望身份验证模型中的电子邮件和密码映射到用户模型中的电子邮件和密码,因此在我的MappingProfile中我有:

public UserProfile()
    {
        CreateMap<User, Authentication>()
            .ForMember(dest => dest.Email, o => o.MapFrom(src => src.Email))
            .ForMember(dest => dest.Password, o => o.MapFrom(src => src.Password))
            .IgnoreAllNonExisting();
    }

The IgnoreAllNonExisting is a custom extension like so: IgnoreAllNonExisting是一个自定义扩展,如下所示:

   public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>
        (this IMappingExpression<TSource, TDestination> expression)
    {
        var flags = BindingFlags.Public | BindingFlags.Instance;
        var sourceType = typeof(TSource);
        var destinationProperties = typeof(TDestination).GetProperties(flags);

        foreach (var property in destinationProperties)
        {
            if (sourceType.GetProperty(property.Name, flags) == null)
            {
                expression.ForMember(property.Name, opt => opt.Ignore());
            }
        }
        return expression;
    }

Despite the extension I still get this error: 尽管扩展我仍然得到这个错误:

Unmapped properties:Firstname;Lastname 未映射的属性:名字;姓氏

It's almost as if my extension is just being ignored? 这几乎就像我的扩展被忽略了?

Does anyone know what im doing wrong? 有谁知道我做错了什么?

Need to create the mappings from User to Authentication and vice-versa (not one mapping for both directions). 需要创建从用户身份验证的映射,反之亦然(不是两个方向的映射)。

Since the names of properties are the same for User and Authentication the AutoMapper makes the automatic mapping. 由于用户身份验证的属性名称相同,因此AutoMapper会进行自动映射。

The extension method IgnoreAllNonExisting is not needed, the AutoMapper makes this work for you. 不需要扩展方法IgnoreAllNonExisting ,AutoMapper使您可以使用它。

public static void Test01()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<User, Authentication>();
        cfg.CreateMap<Authentication, User>();
    });

    var mapper = config.CreateMapper();

    var authentication = mapper.Map<User, Authentication>(new User { Email = "email", Password = "pass", Firstname = "first", Lastname = "last" });

    var user = mapper.Map<Authentication, User>(new Authentication { Email = "email", Password = "pass" });
}

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

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