【发布时间】:2009-10-23 10:47:50
【问题描述】:
我正在使用 EF 尝试使用 ASP.NET 更新实体。我正在创建一个实体,设置它的属性,然后将其传递回具有 ID 的单独层上的 EF,以便可以应用更改。我这样做是因为我只在实体绑定到 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 中使用它时似乎遇到了一些问题。
【问题讨论】:
标签: asp.net entity-framework foreign-keys