具有复杂类型的AutoMapper

试图在AutoMapper中使用复杂类型时遇到问题。

我有两个对象,一个域和一个在我的视图中使用的ViewModel;

视图模型

public class RegisterCoupleModel
{
    [Required(ErrorMessage = "campo obrigatório")]
    [Display(Name = "Primeiro nome", Order = 0, GroupName = "Noivo")]
    [StringLength(60)]
    public string FistNameGroom
    {
        get;
        set;
    }

    [Required(ErrorMessage = "campo obrigatório")]
    [Display(Name = "Último nome", Order = 1, GroupName = "Noivo")]
    [StringLength(60)]
    public string LastNameGroom
    {
        get;
        set;
    }

    [Required(ErrorMessage = "campo obrigatório")]
    [RegularExpression(@"^[w-.]+@([w-]+.)+[w-]{2,4}$", ErrorMessage = "Formato de email inválido.")]
    [DataType(DataType.EmailAddress)]
    [Remote("IsEmailAvailable", "Validation", "", ErrorMessage = "este email já está sendo usado por outro usuário.")]
    [Display(Name = "Email", Order = 2, GroupName = "Noivo")]
    [StringLength(180)]
    public string EmailGroom
    {
        get;
        set;
    }

    [Required(ErrorMessage = "campo obrigatório")]
    [Display(Name = "Primeiro nome", Order = 0, GroupName = "Noiva")]
    [StringLength(60)]
    public string FistNameBride
    {
        get;
        set;
    }

    [Required(ErrorMessage = "campo obrigatório")]
    [Display(Name = "Último nome", Order = 1, GroupName = "Noiva")]
    [StringLength(60)]
    public string LastNameBride
    {
        get;
        set;
    }

    [Required(ErrorMessage = "campo obrigatório")]
    [RegularExpression(@"^[w-.]+@([w-]+.)+[w-]{2,4}$", ErrorMessage = "Formato de email inválido.")]
    [DataType(DataType.EmailAddress)]
    [Remote("IsEmailAvailable", "Validation", "", ErrorMessage = "este email já está sendo usado por outro usuário.")]
    [Display(Name = "Email", Order = 2, GroupName = "Noiva")]
    [StringLength(180)]
    public string EmailBride
    {
        get;
        set;
    }

    [Required(ErrorMessage = "campo obrigatório")]
    [Display(Name = "Url")]
    [RegularExpression(@"^[a-zA-Z0-9_-.+]{5,22}$", ErrorMessage = "Chave inválida")]
    [StringLength(22, MinimumLength = 5, ErrorMessage = "A chave deve ter entre {0} e {1} caracteres.")]
    [Remote("IsKeywordAvaliable", "Validation")]
    public string UrlKeyword
    {
        get;
        set;
    }

    [Display(Name = "Voce é humano?")]
    [UIHint("ReCaptcha")]
    public string ReCaptcha
    {
        get;
        set;
    }
}

域对象

public class Couple
{
    [Key]
    public Guid Id { get; set; }
    public string UrlKeyword { get; set; }
    public virtual Partner Groom { get; set; }
    public virtual Partner Bride { get; set; }
    public DateTime Marriage { get; set; }
    public DateTime Dating { get; set; }
    public DateTime Engagement { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

如果你看,你会看到我的对象Couple域有属性有BrideGroom这是实际上是相同的类型

如何映射我的域对象与RegisterCoupleModel Couple

我在这里做到了:

在设置automapper试图做一些事情:

CreateMap<RegisterCoupleModel, Couple>()
    .ForMember(dest => dest.Bride.User.FirstName, opt => opt.MapFrom(source => source.FistNameBride))
    .ForMember(dest => dest.Bride.User.LastName, opt => opt.MapFrom(source => source.LastNameBride))
    .ForMember(dest => dest.Bride.User.Email, opt => opt.MapFrom(source => source.EmailBride))
    .ForMember(dest => dest.Groom.User.FirstName, opt => opt.MapFrom(source => source.FistNameGroom))
    .ForMember(dest => dest.Groom.User.LastName, opt => opt.MapFrom(source => source.LastNameGroom))
    .ForMember(dest => dest.Groom.User.Email, opt => opt.MapFrom(source => source.EmailGroom));

但是显示下面的错误:

表达式'dest => dest.Bride.User.FirstName'必须解析为顶级成员。 参数名称:lambdaExpression

我知道这需要尝试使用嵌套类型映射属性。

但是,我怎样才能将RegisterCoupleModel映射到Couple并且这两个属性BrideGroom是相同的类型?

我在StackOverflow上发现了一个问题,看起来像这样,但它对我有帮助。


我要做的是将FirstNameBrideLastNameBrideEmailBrideFirstNameGroomLastNameGroomEmailGroom的属性封装成嵌套的viewmodel类型,让我们说PersonDetails

public class PersonDetails
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string Email { get; set; }
}

并相应地更新您的父虚拟机:

public class RegisterCoupleModel
{
   public PersonDetails GroomDetails { get; set; }
   public PersonDetails BrideDetails { get; set; }
}

然后,您可以提供从PersonDetailsUser (或任何类型的Groom.User)的映射:

Mapper.CreateMap<PersonDetails,User>();

注意我如何得到如此明确的属性映射 - >因为这些字段在源和目标中具有相同的名称,所以不需要显式映射。 请尽可能地尝试并做到这一点。 代码越少 - >代码越好。

然后除了上面的映射之外,只需执行以下操作:

Mapper.CreateMap<RegisterCoupleModel, Couple>();

AutoMapper将看到RegisterCoupleModel有两个PersonDetails对象,看它有一个映射定义,然后自动使用它。

这应该工作(我以前做过)。

你不应该总是使用平面视图模型,在必要时嵌套它们(例如重用字段)。

链接地址: http://www.djcxy.com/p/37385.html

上一篇: AutoMapper with complex types

下一篇: AutoMapper flattening of nested mappings asks for a custom resolver