gpt4 book ai didi

asp.net - Entity Framework 与相关实体更新

转载 作者:行者123 更新时间:2023-12-01 11:09:27 25 4
gpt4 key购买 nike

我正在使用 EF 尝试使用 ASP.NET 更新实体。我正在创建一个实体,设置它的属性,然后将它传递回带有 ID 的单独层上的 EF,以便可以应用更改。我这样做是因为我只在实体绑定(bind)到 UI 控件时才存储它的 ID。

一切都适用于标准属性,但我无法更新产品(相关实体)的 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 一起使用时遇到了一些问题。

最佳答案

失败的原因有两个。

  1. 为了更新引用(即 Product.Category),您还必须在上下文中具有原始引用值。
  2. ApplyPropertyChanges(...) 仅适用于实体的常规/标量属性,引用保持不变

所以我会做这样的事情(注意这段代码大量使用了一个叫做 stub entities 的技巧来避免乱用 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();
}
}

假设没有拼写错误等,这将完成工作。

关于asp.net - Entity Framework 与相关实体更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1612655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com