【问题标题】:Error with AutoMapper between model and viewmodel: Missing type map configuration or unsupported mapping模型和视图模型之间的 AutoMapper 出错:缺少类型映射配置或不支持的映射
【发布时间】:2015-03-19 06:43:34
【问题描述】:

好吧,我正在尝试将我的用户配置文件模型映射到用户配置文件视图模型/从用户配置文件视图模型映射,但由于它们不共享所有数据字段,因此它不起作用:

型号:

    public class UserProfile
{
    public virtual string Id { get; set; }
    public virtual string Interests { get; set; }
    public virtual string Biography { get; set; }
    public virtual string SmokingAttitude { get; set; }
    public virtual string DrinkingAttitude { get; set; }
    public virtual string Projects { get; set; }
    public virtual string Groups { get; set; }
}

视图模型:

    public class UserProfileViewModel
{
    [Display(Name = "Interests")]
    public string Interests { get; set; }

    [Display(Name = "Biography/Comments")]
    public string Biography { get; set; }

    [Display(Name = "Attitude to Smoking")]
    public string SmokingAttitude { get; set; }

    [Display(Name = "Attitude to Drinking")]
    public string DrinkingAttitude { get; set; }

    [Display(Name = "Projects working on")]
    public string Projects { get; set; }

    [Display(Name = "Groups joined")]
    public string Groups { get; set; }


    public IEnumerable<SelectListItem> AttitudeList
    {
        get
        {
            return new[]{
                new SelectListItem {Value = "not specified", Text = "not specified"},
                new SelectListItem {Value = "very negative", Text = "very negative"},
                new SelectListItem {Value = "negative", Text = "negative"}, 
                new SelectListItem {Value = "compromisable",  Text = "compromisable"},
                new SelectListItem {Value = "neutral", Text = "neutral"},
                new SelectListItem {Value = "positive", Text = "positive"},
            };
        }
    }
}

如您所见,ID 属性存储在用户配置文件模型中(作为用户表的键),而不是用户配置文件视图模型。但是,用户配置文件视图模型具有为选择/下拉列表操作定义的附加字段 AttitudeList。我认为这是 automapper 无法正常工作的原因,但我完全不知道如何解决这个问题。

有人可以帮忙吗?这个想法只是将公共字段从模型映射到视图模型/从视图模型映射,同时忽略不同的字段。我希望我不必只是手动映射它们编写数十行代码...

【问题讨论】:

    标签: c# asp.net-mvc model-view-controller asp.net-mvc-5 automapper


    【解决方案1】:

    忽略该属性。

    Mapper.CreateMap<UserProfile, UserProfileViewModel>()
            .Ignore(dst => dst.AttitudeList);
    

    Ignore mapping one property with Automapper

    【讨论】:

    • 我明白了,如果要忽略的字段数量为 1-2,它会很好用,但如果模型和视图模型都有 2-3+ 不匹配的字段,它仍然会变得很大和混乱。有没有办法简单地忽略任何不常见的字段?或者这是不可能的?
    • “忽略其余部分”的问题是,如果您输入错误,它会静默中断。你总是可以做 ReverseMap,它保留了忽略。或者,您可以在视图模型上使用 Ignore 属性。
    • 我完全同意 Jimmy Bogard 的观点,我也倾向于手动映射所有属性。这是一些额外的工作,但我保证,如果我稍后重命名属性,不会有任何问题。
    • @VikciaR:似乎我的 AutoMapper 工作方式有点不同,它使用 Map(userProfile) 而不是 CreateMap(UserProfile, UserProfileViewModel)。如果我只使用 Map 而不是 CreateMap,扩展方法似乎不起作用。为什么会发生这种情况,有没有办法解决这个问题?
    猜你喜欢
    • 2019-03-01
    • 2017-04-16
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 2013-01-18
    • 2015-05-07
    相关资源
    最近更新 更多