関連エンティティによるエンティティフレームワークの更新
-
06-07-2019 - |
質問
EFを使用して、ASP.NETでエンティティを更新しようとしています。エンティティを作成し、そのプロパティを設定してから、IDを持つ別のレイヤー上のEFに返して、変更を適用できるようにします。エンティティのIDはUIコントロールにバインドされている場合にのみ保存するため、これを行っています。
すべてが標準のプロパティで機能しますが、製品(関連するエンティティ)のCategory.IDを更新できません。 EntityKey、EntityReferenceおよび他のいくつかを試しましたが、カテゴリIDは保存されません。これは私が持っているものです:
Product product = new Product();
product.CategoryReference.EntityKey = new EntityKey("ShopEntities.Categories", "CategoryID", categoryId);
product.Name = txtName.Text.Trim();
... other properties
StockControlDAL.EditProduct(productId, product);
public static void EditProduct(int productId, Product product) {
using(var context = new ShopEntities()) {
var key = new EntityKey("ShopEntities.Products", "ProductID", productId);
context.Attach(new Product() { ProductID = productId, EntityKey = key });
context.AcceptAllChanges();
product.EntityKey = key;
product.ProductID = productId;
context.ApplyPropertyChanges("ShopEntities.Products", product);
context.SaveChanges();
}
}
本当にEFを使用したいのですが、ASP.NETでEFを使用する際にいくつかの問題があるようです。
解決
これはこの質問に対する回答として受け入れられています Strongly-Typed ASP.NETエンティティフレームワークを使用したMVC
context.AttachTo(product.GetType().Name, product);
ObjectStateManager stateMgr = context.ObjectStateManager;
ObjectStateEntry stateEntry = stateMgr.GetObjectStateEntry(model);
stateEntry.SetModified();
context.SaveChanges();
試しましたか?
[更新、上部のコードは機能しません]
これは私が使用した小さな拡張プロパティであるため、次のコードブロックは理解しやすいです。
public partial class Product
{
public int? CategoryID
{
set
{
CategoryReference.EntityKey = new EntityKey("ShopEntities.Categories", "CategoryID", value);
}
get
{
if (CategoryReference.EntityKey == null)
return null;
if (CategoryReference.EntityKey.EntityKeyValues.Count() > 0)
return (int)CategoryReference.EntityKey.EntityKeyValues[0].Value;
else
return null;
}
}
}
そしてそれは私のために働いた(今回は確かに):
System.Data.EntityKey key = new System.Data.EntityKey("ShopEntities.Products", "ProductID", productId);
object originalItem;
product.EntityKey = key;
if (context.TryGetObjectByKey(key, out originalItem))
{
if (originalItem is EntityObject &&
((EntityObject)originalItem).EntityState != System.Data.EntityState.Added)
{
Product origProduct = originalItem as Product;
origProduct.CategoryID == product.CategoryID;//set foreign key again to change the relationship status
context.ApplyPropertyChanges(
key.EntitySetName, product);
}
}context.SaveChanges();
確かにハックに見えます。その理由は、EF関係のエンティティ(変更、追加、削除)としてのステータスがあり、そのステータスに基づいて、EFが外部キーの値を変更するか、多対多の関係がある場合に行を削除するためだと思います。何らかの理由で(理由はわかりません)、関係のステータスはプロパティのステータスと同じように変更されません。そのため、リレーションシップのステータスを変更するためにoriginalItemにCategoryReference.EntityKeyを設定する必要がありました。
他のヒント
これが失敗する理由は2つあります。
- 参照(つまりProduct.Category)を更新するには、コンテキスト内の元の参照値も持っている必要があります。
- ApplyPropertyChanges(...)は、エンティティの通常/スカラープロパティにのみ適用され、参照は変更されないままになります
だから私はこのようなことをします(このコードはスタブエンティティを使用して、EntityKeysをいじるのを回避します)
Product product = new Product();
// Use a stub because it is much easier.
product.Category = new Category {CategoryID = selectedCategoryID};
product.Name = txtName.Text.Trim();
... other properties
StockControlDAL.EditProduct(productId, originalCategoryID);
public static void EditProduct(Product product, int originalCategoryID ) {
using(var context = new ShopEntities())
{
// Attach a stub entity (and stub related entity)
var databaseProduct = new Product {
ProductID = product.ProductID,
Category = new Category {CategoryID = originalCategoryID}
};
context.AttachTo("Products", databaseProduct);
// Okay everything is now in the original state
// NOTE: No need to call AcceptAllChanges() etc, because
// Attach puts things into ObjectContext in the unchanged state
// Copy the scalar properties across from updated product
// into databaseProduct in the ObjectContext
context.ApplyPropertyChanges("ShopEntities.Products", product);
// Need to attach the updated Category and modify the
// databaseProduct.Category but only if the Category has changed.
// Again using a stub.
if (databaseProduct.Category.CategoryID != product.Category.CategoryID)
{
var newlySelectedCategory =
new Category {
CategoryID = product.Category.CategoryID
};
context.AttachTo("Categories", newlySelectedCategory)
databaseProduct.Category = newlySelectedCategory;
}
context.SaveChanges();
}
}
これは、タイプミスがないと仮定して、仕事をします。