zoukankan      html  css  js  c++  java
  • 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();
    }
  • 相关阅读:
    python mymsql sqlalchemy
    python中 wraps 的作用
    python Subprocess的使用
    实现一个命令分发器
    实现一个cache装饰器,实现过期可清除功能
    求2个字符串的最长公共子串
    Base64编码,解码的实现
    把一个字典扁平化
    hihocoder1415 重复旋律3
    hihocoder 1407 重复旋律2
  • 原文地址:https://www.cnblogs.com/chriskwok/p/1604195.html
Copyright © 2011-2022 走看看