問題を説明するためにNorthwindデータベースで小さなプロジェクトを作成しました。ここMVCを編集したEntity Framework 4.3では複雑なオブジェクトは保存されません
は、コントローラのアクションである:
[HttpPost]
public ActionResult Edit(Product productFromForm)
{
try
{
context.Products.Attach(productFromForm);
var fromBD = context.Categories.Find(productFromForm.Category.CategoryID);
productFromForm.Category = fromBD;
context.Entry(productFromForm).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
コンテキストはnew DatabaseContext()
としてコントローラのコンストラクタでインスタンス化されます。
public class DatabaseContext:DbContext
{
public DatabaseContext()
: base("ApplicationServices") {
base.Configuration.ProxyCreationEnabled = false;
base.Configuration.LazyLoadingEnabled = false;
}
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder){
modelBuilder.Configurations.Add(new ProductConfiguration());
modelBuilder.Configurations.Add(new CategoriesConfiguration());
}
private class ProductConfiguration : EntityTypeConfiguration<Product> {
public ProductConfiguration() {
ToTable("Products");
HasKey(p => p.ProductID);
HasOptional(p => p.Category).WithMany(x=>x.Products).Map(c => c.MapKey("CategoryID"));
Property(p => p.UnitPrice).HasColumnType("Money");
}
}
private class CategoriesConfiguration : EntityTypeConfiguration<Category> {
public CategoriesConfiguration() {
ToTable("Categories");
HasKey(p => p.CategoryID);
}
}
}
public class Category {
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class Product {
public int ProductID { get; set; }
public string ProductName { get; set; }
public string QuantityPerUnit { get; set; }
public decimal UnitPrice { get; set; }
public Int16 UnitsInStock { get; set; }
public Int16 UnitsOnOrder { get; set; }
public Int16 ReorderLevel { get; set; }
public bool Discontinued { get; set; }
public virtual Category Category { get; set; }
}
問題は、製品からは何も保存できますが、カテゴリの変更は保存できないということです。
productFromFormオブジェクトには、productFromForm.Product.ProductID内の新しいCategoryIDが問題なく含まれています。しかし、私はFind()
コンテキストからオブジェクトを取得するカテゴリを取得するときに、名前と説明を持たないオブジェクト(NULLにとどまりません)と、Category
のIDが変更されたとしてもSaveChanges()
は参照を変更しません。
理由は何ですか?
Categoryナビゲーション参照の代わりにproduct.CategoryIDを設定するとどうなりますか? – Dismissile
productFromFormには既にフォームから.CategoryIDが正しく入力されています。 –
ああ、私は自分のエンティティをコントローラで直接使用しないので、わかりませんでした。 – Dismissile