【发布时间】:2018-03-08 21:46:49
【问题描述】:
我正在尝试使用 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-form。
目前,当我配置映射器时,我会忽略 CreateCommentForm 属性,只是为了避免遇到 AutoMapper 异常。但是如何通过将 Id 属性传递给对象来告诉自动映射器每次都创建一个新实例?
mapper.CreateMap<Blog, BlogViewModel>().ForMember(dest => dest.CreateCommentForm , opts => opts.Ignore() );
如何通过使用 AutoMapper 传递 Blog.Id 属性将 CreateCommentForm 正确映射到新实例?
【问题讨论】:
标签: c# automapper