ObjectContext的ApplyPropertyChanges()方法不能更新导航属性的解决办法

Entity Object中往往需要在中间层返回一个Dto对象给前端,修改后将这个离线的Dto传回中间层更新,ApplyPropertyChanges方法很方便的帮我们把修改属性应用到上下文的对象(注意该对象必须是Modified或Unchanged),然后SaveChanged即可更新到数据库,然后实践过程发现无法更新导航属性,经过反复查资料做测试,需要做如下处理才能成功实现:

public void UpdateProduct(Product updated, Category category, Model model)
{
//如果product不是来自_context这个ObjectContext则需要使用下面语句
Product original = _context.Product.FirstOrDefault(a => a.ProductID == updated.ProductID);
if (category != null && original.ProductCategory.CategoryId != category.CategoryId) original.ProductCategory = category;
original.ProductModel
= null; original.ProductModel = model;
if (original.EntityState == EntityState.Unchanged) _context.Attach(original);
_context.ApplyPropertyChanges(original.EntityKey.EntitySetName, updated);
//导航属性无法直接应用,需要使用上面两句
_context.SaveChanges();
}
原文地址:https://www.cnblogs.com/chriskwok/p/1604195.html