2011-01-10 1 views
1

Я заинтересован в наилучшем способе взаимодействия с внешними ключевыми отношениями при использовании ASP.NET MVC и Entity Framework.Редактирование/создание объекта EF с помощью внешних ключей

В настоящее время я использую ViewModel для вывода страницы создания и редактирования (с использованием частичного), но все не так хорошо работает, когда я могу отправить данные обратно.

Перед тем, как проверить свою модель, я использую опубликованное значение из списка выбора, чтобы найти посторонний объект и назначить его моей модели, но когда я использую UpdateModel при редактировании, ссылки заканчиваются нулевым, я предполагаю, он не может правильно привязать это свойство.

Как люди обычно справляются с этой проблемой? Использование ViewModel для заполнения моих выпадающих меню кажется достаточно сложным, но я должен что-то пропускать, когда дело доходит до редактирования. Обычно люди создают собственное связующее, чтобы обойти эту проблему?

Я пробовал использовать сильную печать и FormCollection.

ViewModel:

public class ReportViewModel 
{ 
    public Report Report { get; set; } 
    public SelectList ReportDeliveryMethods { get; set; } 
    public string ReportDeliveryMethod { get; set; } 
    public SelectList ReportReceivers { get; set; } 
    public string ReportReceiver { get; set; } 
    public SelectList PermitTypes { get; set; } 
    public string PermitType { get; set; } 
} 

Контроллер:

[HttpPost]   
public ActionResult Edit(int id, FormCollection collection) 
     { 
      Report report; 

      try 
      { 
       report = repository.GetReport(id); 

       // Convert ReportDeliveryMethod to Object Reference       
       if (!string.IsNullOrEmpty(collection["ReportDeliveryMethod"])) 
       { 
        int reportDeliveryMethodId = 0; 
        if (int.TryParse(collection["ReportDeliveryMethod"], out reportDeliveryMethodId)) 
        { 
         report.ReportDeliveryMethod = repository.GetReportDeliveryMethod(reportDeliveryMethodId); 
        } 
       } 

       // Convert ReportReceiver to Object Reference    
       if (!string.IsNullOrEmpty(collection["ReportReceiver"])) 
       { 
        int reportReceiverId = 0; 
        if (int.TryParse(collection["ReportReceiver"], out reportReceiverId)) 
        { 
         report.ReportReceiver = repository.GetReportReceiver(reportReceiverId); 
        } 
       } 

       // Convert PermitType to Object Reference    
       if (!string.IsNullOrEmpty(collection["PermitType"])) 
       { 
        int permitTypeId = 0; 
        if (int.TryParse(collection["PermitType"], out permitTypeId)) 
        { 
         report.PermitType = repository.GetPermitType(permitTypeId); 
        } 
       } 

       if (ModelState.IsValid) 
       { 
        UpdateModel(report); 
        repository.Save(); 

        return RedirectToAction("Index"); 
       } 
       else 
       { 
        return View(); 
       } 
      } 
      catch (Exception ex) 
      { 
       return View(); 
      } 
     } 

Форма:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PermitLookup.Models.ReportViewModel>" %> 
<% using (Html.BeginForm()) 
    {%> 
<%: Html.ValidationSummary(true) %> 
<fieldset> 
    <legend>Fields</legend> 
    <div class="editor-label"> 
     <%: Html.LabelFor(model => model.Report.ShareName) %> 
    </div> 
    <div class="editor-field"> 
     <%: Html.TextBoxFor(model => model.Report.ShareName) %> 
     <%: Html.ValidationMessageFor(model => model.Report.ShareName)%> 
    </div> 
    <div class="editor-label"> 
     <%: Html.LabelFor(model => model.Report.Description) %> 
    </div> 
    <div class="editor-field"> 
     <%: Html.TextBoxFor(model => model.Report.Description)%> 
     <%: Html.ValidationMessageFor(model => model.Report.Description)%> 
    </div> 
    <div class="editor-label"> 
     <%: Html.LabelFor(model => model.Report.Frequency)%> 
    </div> 
    <div class="editor-field"> 
     <%: Html.TextBoxFor(model => model.Report.Frequency)%> 
     <%: Html.ValidationMessageFor(model => model.Report.Frequency)%> 
    </div> 
    <div class="editor-label"> 
     <%: Html.LabelFor(model => model.Report.SendTime)%> 
    </div> 
    <div class="editor-field"> 
     <%: Html.TextBoxFor(model => model.Report.SendTime)%> 
     <%: Html.ValidationMessageFor(model => model.Report.SendTime)%> 
    </div> 
    <div class="editor-label"> 
     <%: Html.LabelFor(model => model.Report.ReportDeliveryMethod)%> 
    </div> 
    <div class="editor-field"> 
     <%=Html.DropDownListFor(model => model.ReportDeliveryMethod, Model.ReportDeliveryMethods)%> 
     <%: Html.ValidationMessageFor(model => model.Report.ReportDeliveryMethod)%> 
    </div> 
    <div class="editor-label"> 
     <%: Html.LabelFor(model => model.Report.ReportReceiver)%> 
    </div> 
    <div class="editor-field"> 
     <%=Html.DropDownListFor(model => model.ReportReceiver, Model.ReportReceivers)%> 
     <%: Html.ValidationMessageFor(model => model.Report.ReportReceiver)%> 
    </div> 
    <div class="editor-label"> 
     <%: Html.LabelFor(model => model.Report.PermitType)%> 
    </div> 
    <div class="editor-field"> 
     <%=Html.DropDownListFor(model => model.PermitType, Model.PermitTypes)%> 
     <%: Html.ValidationMessageFor(model => model.Report.PermitType)%> 
    </div> 
    <p> 
     <input type="submit" value="Save" /> 
    </p> 
</fieldset> 
<% } %> 

ответ

1

Рассмотрим ReportDeliveryMethod. В вашей модели зрения, это string. На вашем объекте Report это тип ReportDeliveryMethod. Поскольку string не может быть неявным образом передан в ReportDeliveryMethod, UpdateModel не свяжет его.

Итак, каков ваш выбор?

  1. Карта вручную, как и сейчас.
  2. Привязать идентификатор, а не ссылку на объект. EF 4 поддерживает FK associations. Вы можете поставить ReportDeliveryMethodId в вашей модели модели вместо ReportDeliveryMethod.
+0

Большое спасибо Крейг, это прояснило мою проблему в Create и некоторые из ваших других ответов будут полезны для обновления! –

 Смежные вопросы

  • Нет связанных вопросов^_^