加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

尝试将AutoMapper用于具有子集合的模型,在Asp.Net MVC 3中获取null错误

发布时间:2020-05-23 19:54:56 所属栏目:asp.Net 来源:互联网
导读:我是AutoMapper的新手,我有一个看起来像这样的视图: @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = multipart/form-data })){ @Html.ValidationSummary(true) fieldset legendConsulta

我是AutoMapper的新手,我有一个看起来像这样的视图:

@using (Html.BeginForm(null,null,FormMethod.Post,new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Consultant</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>
        <div class="editor-label">
            Program du behrskar:
        </div>
        <div>
            <table id="programEditorRows">
                <tr>
                    <th>
                        Program
                    </th>
                    <th>
                        Niv
                    </th>
                </tr>
                @foreach (var item in Model.Programs)
                {
                    Html.RenderPartial("ProgramEditorRow",item);
                }
            </table>
            <a href="#" id="addProgram">Lgg till</a>
        </div>
        <div class="editor-label">
            Sprk du behrskar:
        </div>
        <div>
            <table id="languageEditorRows">
                <tr>
                    <th>
                        Sprk
                    </th>
                    <th>
                        Niv
                    </th>
                </tr>
                @foreach (var item in Model.Languages)
                {
                    Html.RenderPartial("LanguageEditorRow",item);
                }
            </table>
            <a href="#" id="addLanguage">Lgg till</a>
        </div>
        <div>
            <table id="educationEditorRows">
                <tr>
                    <th>
                        Utbildning
                    </th>
                    <th>
                        Niv
                    </th>
                </tr>
                @foreach (var item in Model.Educations)
                {
                    Html.RenderPartial("EducationEditorRow",item);
                }
            </table>
            <a href="#" id="addEducation">Lgg till</a>
        </div>
        <div>
            <table id="workExperienceEditorRows">
                <tr>
                    <th>
                        Arbetserfarenhet
                    </th>
                    <th>
                        Startdatum
                    </th>
                    <th>
                        Slutdatum
                    </th>
                </tr>
                @foreach (var item in Model.WorkExperiences)
                {
                    Html.RenderPartial("WorkExperienceEditorRow",item);
                }
            </table>
            <a href="#" id="addWorkExperience">Lgg till</a>
        </div>
        <div>
            <table id="competenceAreaEditorRows">
                <tr>
                    <th>
                        Kompetensomrde
                    </th>
                    <th>
                        Niv
                    </th>
                </tr>
                @foreach (var item in Model.CompetenceAreas)
                {
                    Html.RenderPartial("CompetenceAreaEditorRow",item);
                }
            </table>
            <a href="#" id="addCompetenceArea">Lgg till</a>
        </div>
        <div>
            <input id="fileInput" name="FileInput" type="file" />
        </div>
        <p>
            <input type="submit" value="Spara" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List","Index")
</div>

这是GET Edit方法:

public ActionResult Edit(int id)
    {
        Consultant consultant = _repository.GetConsultant(id);
        ConsultantViewModel vm = Mapper.Map<Consultant,ConsultantViewModel>(consultant);
        return View(vm);
    }

和POST编辑方法:

[HttpPost]
    [ValidateInput(false)] //To allow HTML in description box
    public ActionResult Edit(int id,ConsultantViewModel vm,FormCollection collection)
    {

            Consultant consultant = Mapper.Map<ConsultantViewModel,Consultant>(vm);
            _repository.Save();
            return RedirectToAction("Index");

    }

现在,当AutoMapper创建ViewModel时,它似乎工作正常(使用其最简单的形式,没有解析器或任何东西,只是将Consultant映射到ConsultantViewModel),包括子集合和所有.此外,UserName属性在那里.现在,在视图中我没有UserName的字段,因为它总是由当前用户(User.Identity.Name)自动填充.但是当我返回vm时,UserName属性为null,可能是因为View中没有该字段.

我怀疑一些集合会导致相同的错误,即使我在那里为UserName放置一个隐藏字段,因为它是可选的,以便顾问填写语言等…所以即使ViewModel有一个实例化的列表,每个这些子集合进入View(计数为0),它们返回时返回null值.

我该如何解决这个问题?我不想强迫用户在所有子集合中填充值.我的意思是,我总是可以为Name属性创建一个带有空字符串的Language对象,但这意味着不必要的额外代码,我真正想要的是让孩子集合(和UserName)回到他们进入的方式.视图 – 填写UserName,并且实例化子集合,但如果用户未添加任何项目,则计数为0.

更新:

我不知道,我认为我在某种程度上误解了AutoMapper ……我发现实际上子集合在映射方面确实不是问题,它可以很好地将它映射回Consultant对象.但是……我还需要将id放回Consultant对象中,因为ViewModel没有.但即便如此,当我保存到存储库时,它也不会被保存.这就是我认为我误解了AutoMapper的地方 – 我曾经以为它会以某种方式用ViewModel中的值填充Consultant对象,但我想它会导致顾问变量引用Map()语句中的另一个对象?因为没有一个坚持……

这是修改后的POST方法(不起作用):

[HttpPost]
    [ValidateInput(false)] //To allow HTML in description box
    public ActionResult Edit(int id,FormCollection collection)
    {

        vm.UserName = User.Identity.Name;
        Consultant consultant = _repository.GetConsultant(id);
        consultant = Mapper.Map<ConsultantViewModel,Consultant>(vm);
        consultant.Id = id;
        _repository.Save();
        return RedirectToAction("Index");

    }

我究竟做错了什么?如何将ViewModel中的填充值返回到Consultant对象并将其保存到数据库?

更新2:

好吧,彻底迷茫…开始有点:这是Application_Start中的地图创建:

Mapper.CreateMap<ConsultantViewModel,Consultant>().ForMember("Id",opts => opts.Ignore());
        Mapper.CreateMap<Consultant,ConsultantViewModel>();

编辑方法:

// GET: /Consultant/Edit/5

    public ActionResult Edit(int id)
    {
        Consultant consultant = _repository.GetConsultant(id);
        ConsultantViewModel vm = Mapper.Map<Consultant,ConsultantViewModel>(consultant);
        return View(vm);
    }

    //
    // POST: /Consultant/Edit/5

    [HttpPost]
    [ValidateInput(false)] //To allow HTML in description box
    public ActionResult Edit(int id,FormCollection collection)
    {
        vm.UserName = User.Identity.Name;
        Consultant consultant = _repository.GetConsultant(id);
        consultant = Mapper.Map<ConsultantViewModel,Consultant>(vm,consultant);
        _repository.Save();
        return RedirectToAction("Index");
    }

这也不起作用,但显然至少会尝试更新实体模型,因为现在我得到一个例外:

无法初始化EntityCollection,因为EntityCollection所属的对象的关系管理器已附加到ObjectContext.只应调用InitializeRelatedCollection方法在对象图的反序列化期间初始化新的EntityCollection.

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读