如何配置AutoMapper以将属性设置为对象的新实例?

时间:2018-03-08 21:46:50

标签: c# automapper

我正在尝试使用AutoMapper自动映射我的模型以查看模型。

我有以下两个视图模型

public class CreateComment
{
    [Required]
    public int BlogId { get; set; }

    [Required]
    public string Message { get; set; }

    public CreateComment()
    {

    }

    public CreateComment(int? blogId)
    {
        if(blogId.HasValue)
        {
            BlogId = blogId.Value;
        }
    }
}

public class BlogViewModel 
{
    [Required]
    public string Title { get; set; }

    [Required]
    public string Body { get; set; }
    // There are more

    [Required]
    public int? Id { get; set; }

    [DataType("CommentDisplayViewModelTable")]
    public IEnumerable<CommentDisplayViewModel> Comments { get; set; }

    public CreateComment CreateCommentForm { get; set; }
}

每次映射此对象时,CreateCommentForm属性应该是一个新实例。创建CreateCommentForm的新实例时唯一不同的是,我希望BlogId能够填充给我。这里的想法是有一个空CreateCommentForm来构造html表单。

现在,当我配置映射器时,我忽略CreateCommentForm属性只是为了避免遇到AutoMapper异常。但是,如何通过将Id属性传递给对象来告诉自动映射器每次都创建一个新实例?

mapper.CreateMap<Blog, BlogViewModel>().ForMember(dest => dest.CreateCommentForm , opts => opts.Ignore() );

如何通过使用AutoMapper传递CreateCommentForm属性,将Blog.Id正确映射到新实例?

1 个答案:

答案 0 :(得分:2)

对于自定义对象创建,您可以使用mapper.CreateMap<Blog, BlogViewModel>().ForMember(dest => dest.CreateCommentForm , opts => opts.ResolveUsing(src => new CreateComment(src.Id)) );

"%2Bstr(__import__('base64').b64decode('bHM=')%2B"
相关问题