DbContext的通用合并:如何检查实体是否已准备好? [英] Generic Merge of DbContext: how to check if entity is all ready attached?

查看:198
本文介绍了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);
            }
        }
    }

我如何一般地确定一个实体存在于上下文中。

How can I generically determine if an entity exists in the context.

推荐答案

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

This is an extension method that looks for an object in a context's state manager by the following steps:


  • 获取类型的关键属性

  • 获取对象的键值

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

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);

这篇关于DbContext的通用合并:如何检查实体是否已准备好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆