EF 4.1-子コレクションのプロパティを更新します
-
22-10-2019 - |
質問
私はこんにちはと低く検索しました、そして私はここで立ち往生しています。
MVC3アプリでEF 4.1を使用しています。サービス/リポジトリ/UnitofWorkパターンとAutomApperを使用して、モデルとエンティティをマッピングしています。
だから私は本当に基本的な状況を持っています。のコレクションがあります ChildProducts
のコレクションがあります PriceTiers
.
私のビューモデルは次のように見えます:
AddityIldProductModel
public class AddEditChildProductModel
{
#region "Fields/Properties"
public ActionType ActionType { get; set; }
public string FormAction { get; set; }
public int ID { get; set; }
public int ProductID { get; set; }
public string Sku { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Cost { get; set; }
public decimal MSRP { get; set; }
public decimal RetailPrice { get; set; }
public int Servings { get; set; }
public decimal Weight { get; set; }
public bool Display { get; set; }
public int DisplayIndex { get; set; }
public IEnumerable<AddEditPriceTierModel> PriceTiers { get; set; }
#endregion
#region "Constructor(s)"
#endregion
#region "Methods"
#endregion
}
追加されたpricetiermodel
public class AddEditPriceTierModel
{
#region "Fields/Properties"
public int ID { get; set; }
public int ChildProductID { get; set; }
public decimal Price { get; set; }
public int QuantityStart { get; set; }
public int QuantityEnd { get; set; }
public bool IsActive { get; set; }
#endregion
#region "Constructor(s)"
#endregion
#region "Methods"
#endregion
}
コントローラーのアクションでは、変更されたものをマップしようとしています PriceTier
プロパティ:
public ActionResult EditChildProduct(AddEditChildProductModel model)
{
if (!ModelState.IsValid)
return PartialView("AddEditChildProduct", model);
ChildProduct childProduct = productService.GetChildProductByID(model.ID);
AutoMapper.Mapper.Map<AddEditChildProductModel, ChildProduct>(model, childProduct);
UnitOfWork.Commit();
return ListChildProducts(model.ProductID);
}
そして、私はこのエラーを取得しています:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
アクションに足を踏み入れると、モデル/エンティティが正しくマッピングされます。
解決
Erangaは正しいです。私はあなたのProductserviceが子育てを返す前にEFコンテキストでアスノタックを呼び出すことはないと推測しています。そうでない場合、これはそれが返すものがまだコンテキストに添付されていることを意味します。 Automapperがそのことを行うと、コレクション全体に取って代わります。コレクションは、フォームの提出の一部ではなかった添付の子団体を孤立させることができます。孤児は非ヌルの外部キーを持っていないため、SaveChangesを呼び出す前にコンテキストから削除する必要があります。そうでない場合は、この悪名高い例外が得られます。
一方、エンティティを返す前にProductserviceがコンテキストでaSnotrackを呼び出す場合、変更は変更されず、Automapperが作成したコレクションに存在しない孤立したアイテムを削除しようとはしません。