zoukankan      html  css  js  c++  java
  • EntityFramework实体更新操作

      Error Info:“An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key”.

    Explanation:

    You must check if an entity with the same key is already tracked by the context and modify that entity instead of attaching the current one.

    The code should be wrighten like this:

    public override void Update(T entity) where T : IEntity {
        if (entity == null) {
            throw new ArgumentException("Cannot add a null entity.");
        }
    
        var entry = _context.Entry<T>(entity);
    
        if (entry.State == EntityState.Detached) {
            var set = _context.Set<T>();
            T attachedEntity = set.Find(entity.Id);  // You need to have access to key
    
            if (attachedEntity != null) {
                var attachedEntry = _context.Entry(attachedEntity);
                attachedEntry.CurrentValues.SetValues(entity);
            } else {
                entry.State = EntityState.Modified; // This should attach entity
            }
        }
    }  
  • 相关阅读:
    java基础-对象
    java基础-类
    java基础-数组
    java基础-for循环、while循环相关
    java基础-程序执行流程之if-else语句
    ODBC, OLEDB, ADO, ADO.NET
    无题
    优秀资源
    SSRS Report Knowledge Base
    SSRS 通过Customer Code访问Dataset
  • 原文地址:https://www.cnblogs.com/super86/p/2950742.html
Copyright © 2011-2022 走看看