0

私はEntityFrameworkを使用しています。1 つまたはゼロの CertificateReasons を持つことができる "Application" オブジェクト (フィールド certificateReasonID を持つ) があります。そのため、"CertificateReason" テーブルとの関係があり、edmx ダイアグラムでは、certificateReasonTypeID フィールドが表示されません。

アプリケーションを更新すると、Application.certificateReasonTypeIDを選択したIDに更新する代わりに、新しいCertificateReasonを挿入し、Application.certificateReasonTypeIDを新しいIDに更新します。

CertificateReason オブジェクトは追加された状態です (技術的に正しい)。aspxコードは

<%foreach (var certReason in Model.CertificateReasons)                  
                  { %>
                        <li>
                        <%= Html.RadioButton("CertificateReason.id", certReason.id)%>
                        <!-- only because it is adding when it shouldn't -we have to set the other non null values(i.e. not id) in the object else it will fail when it tries to save-->
                          <input type="hidden" value="<%= certReason.meaning %>" name="CertificateReason.meaning"/>
                            <input type="hidden" value="<%= certReason.effectiveFrom %>" name="CertificateReason.effectiveFrom"/>
                            <input type="hidden" value="<%= certReason.createdWhen %>" name="CertificateReason.createdWhen"/>
                        <label for="certificateReasonTypeID<%=certReason.meaning%>"><%=certReason.meaning%></label>
                        </li>
                <%}%>

アップデートコードは

 public ActionResult Edit(int id, FormCollection collection, ApplicationViewModel model)
 {
     var appToUpdate = OMF.Application.First(m => m.id == id);
     UpdateModel(movieToUpdate, collection.ToValueProvider()); 
     if (ModelState.IsValid)
     {

          OMF.ApplyPropertyChanges(movieToUpdate.EntityKey.EntitySetName, appToUpdate );
          OMF.SaveChanges();
      }
}

ありがとう

4

1 に答える 1

0

答えは、アプリケーションモデルを編集ポストに渡すことでした-オブジェクトが正しく入力されるようにフォームに非表示フィールドを配置する必要がありました)、varではなくアプリケーションobjetcを取得していることを確認してください。ModelState.IsValid を常に false として使用することはできませんが、挿入ではなく正しく更新されます。他のポイントは、取得時に .Include("CertificateReasons") を実行する必要がありました。

public ActionResult Edit(アプリアプリ、FormCollectionコレクション) {

        Application movieToEdit = OMF.GetApplication(app.id);           
        if(app.CertificateReason != null)
            movieToEdit.CertificateReason = OMF.CertificateReason.First(d => d.id == app.CertificateReason.id);
        TryUpdateModel(movieToEdit);

        //if (ModelState.IsValid) --can't use this
       // {
            OMF.SaveChanges();
       // }
        return RedirectToAction("Edit", app.id);

    }
于 2010-01-11T22:12:43.403 に答える