entity-framework-6 - DbContext的通用合并: how to check if entity is all ready attached?

标签 entity-framework-6 dbcontext

给出以下代码:

    void MergeDbContext(DbContext aSourceDbContext, DbContext aDestinationDbContext)
    {
        var sourceEntities = aSourceDbContext.ChangeTracker.Entries().ToList();
        foreach (DbEntityEntry entry in sourceEntities)
        {
            object entity = entry.Entity;
            entry.State = EntityState.Detached;

            // check if entity is all ready in aDestinationDbContext if not attach
            bool isAttached = false;// TODO I don't know how to check if it is all ready attched.
            if (!isAttached)
            {
                aDestinationDbContext.Set(entity.GetType()).Attach(entity);
            }
        }
    }

我如何一般性地确定上下文中是否存在实体。

最佳答案

这是一种扩展方法,它通过以下步骤在上下文的状态管理器中查找对象:

  • 获取类型的键属性
  • 获取对象的键值
  • 检查上下文中是否存在任何具有对象类型和键值的实体。


  • public static bool IsAttached<T>(this DbContext context, T entity)
        where T : class
    {
        if (entity == null) return false;
    
        var oc = ((IObjectContextAdapter)context).ObjectContext;
    
        var type = ObjectContext.GetObjectType(entity.GetType());
    
        // Get key PropertyInfos
        var propertyInfos = oc.MetadataWorkspace
              .GetItems(DataSpace.CSpace).OfType<EntityType>()
              .Where(i => i.Name == type.Name)
              .SelectMany(i => i.KeyProperties)
              .Join(type.GetProperties(), ep => ep.Name, pi => pi.Name, (ep,pi) => pi);
    
        // Get key values
        var keyValues = propertyInfos.Select(pi => pi.GetValue(entity)).ToArray();
    
        // States to look for    
        var states = System.Data.Entity.EntityState.Added|System.Data.Entity.EntityState.Modified
                    |System.Data.Entity.EntityState.Unchanged|System.Data.Entity.EntityState.Deleted;
    
         // Check if there is an entity having these key values
        return oc.ObjectStateManager.GetObjectStateEntries(states)
                 .Select(ose => ose.Entity).OfType<T>()
                 .Any(t => propertyInfos.Select(i => i.GetValue(t))
                                        .SequenceEqual(keyValues));
    }
    

    用法:

    bool isAttached = dbContext.IsAttached(entity);
    

    关于entity-framework-6 - DbContext的通用合并: how to check if entity is all ready attached?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30577900/

    相关文章:

    .net - 带有 Entity Framework 6.2 的 Azure Function V2

    c# - DbContext的第三方实现,如何同时实现IdentityDbContext

    entity-framework - Asp.Net MVC 5 中的多对多关系与身份表和自定义表

    c# - EF - WithOptional - 左外连接?

    c# - 网络核心 DbContextPool 与 AddDbContextPool 等

    c# - 在 Entity Framework 上运行原始 SQL 查询的 KeyValuePair

    mysql - 使用多个dbcontexts并且找不到原始数据库

    c# - 长期使用Entities时在C#中使用EntityFramework

    c# - 影响如何在 EF 6 代码优先中从数据库创建实体类

    c# - LINQ to Entities 无法识别方法 IsNullOrWhiteSpace