C# 检查实体框架上下文是否正在跟踪实体

C# 检查实体框架上下文是否正在跟踪实体,c#,generics,entity-framework-6,C#,Generics,Entity Framework 6,我有一个代码块,用于检查我的上下文是否正在跟踪实体。如果是,我需要拆下它。这适用于给定的T类型 public virtual async Task<bool> InsertOrUpdate(TE entity) { if (entity.Id == 0 || entity.Id == ModelState.New) { // attach new entity _context.Entry(entity).State = EntityS

我有一个代码块,用于检查我的上下文是否正在跟踪实体。如果是,我需要拆下它。这适用于给定的T类型

public virtual async Task<bool> InsertOrUpdate(TE entity)
{
    if (entity.Id == 0 || entity.Id == ModelState.New)
    {
        // attach new entity
        _context.Entry(entity).State = EntityState.Added;
    }
    else
    {
        // Sometimes when you want to update a detached entity, before attempting to attach it (by setting the .State property),
        // you first need to make sure the entity isn't already attached and being tracked. If this is the case, the existing entity
        // needs to be detached, and the updated entity, attached.
        var attachedEntity = _context.ChangeTracker.Entries<TE>().FirstOrDefault(e => e.Entity.Id == entity.Id);
        if (attachedEntity != null)
        {
            // the entity you want to update is already attached, we need to detach it and attach the updated entity instead
            _context.Entry<TE>(attachedEntity.Entity).State = EntityState.Detached;
        }

        _context.Entry<TE>(entity).State = EntityState.Modified; // Attach entity, and set State to Modified.
        _context.Entry<TE>(entity).Property(o => o.CreatedUserId).IsModified = false;
        _context.Entry<TE>(entity).Property(o => o.CreatedDate).IsModified = false;
    }

    return await _context.SaveChangesAsync() > 0;
}
公共虚拟异步任务插入更新(TE实体)
{
if(entity.Id==0 | | entity.Id==ModelState.New)
{
//附加新实体
_context.Entry(entity.State=EntityState.Added;
}
其他的
{
//有时,当您想要更新分离的实体时,在尝试附加它之前(通过设置.State属性),
//您首先需要确保该实体尚未被附加和跟踪。如果是这种情况,则现有实体
//需要分离并附加更新的实体。
var attachedEntity=_context.ChangeTracker.Entries().FirstOrDefault(e=>e.Entity.Id==Entity.Id);
如果(附件身份!=null)
{
//您要更新的实体已附加,我们需要将其分离并附加更新的实体
_Entry(attachedEntity.Entity).State=EntityState.Distached;
}
_context.Entry(entity.State=EntityState.Modified;//附加实体,并将状态设置为Modified。
_context.Entry(entity).Property(o=>o.CreatedUserId).IsModified=false;
_context.Entry(entity).Property(o=>o.CreatedDate).IsModified=false;
}
return wait_context.SaveChangesAsync()>0;
}
我现在需要更改该方法,以便它在给定的T实体参数内获取IEntity类型的所有对象,然后对找到的每个对象执行相同的逻辑,但是我在设置ChangeTracker.Entries时遇到问题,因为我需要在foreach中将T类型设置为当前选定的类型。我不知道怎么做

public virtual async Task<bool> InsertOrUpdate(TE entity)
{
    //// Find all instances of IEntity within TE: 
    ////  * IF entity is new we set State to EntityState.Added (INSERT)
    ////  * IF entity is existing, we set State to EntityState.Modified (UPDATE)
    List<IEntity> found = FindAllInstances<IEntity>(entity);
    foreach (IEntity ent in found)
    {
        if (entity.Id == 0 || entity.Id == ModelState.New)
        {
            // attach new entity
            _context.Entry(entity).State = EntityState.Added;
        }
        else
        {
            // Sometimes when you want to update a detached entity, before attempting to attach it (by setting the .State property),
            // you first need to make sure the entity isn't already attached and being tracked. If this is the case, the existing entity
            // needs to be detached, and the updated entity, attached.
            var attachedEntity = _context.ChangeTracker.Entries<TE>().FirstOrDefault(e => e.Entity.Id == entity.Id);
            if (attachedEntity != null)
            {
                // the entity you want to update is already attached, we need to detach it and attach the updated entity instead
                _context.Entry<TE>(attachedEntity.Entity).State = EntityState.Detached;
            }

            _context.Entry<TE>(entity).State = EntityState.Modified; // Attach entity, and set State to Modified.
            _context.Entry<TE>(entity).Property(o => o.CreatedUserId).IsModified = false;
            _context.Entry<TE>(entity).Property(o => o.CreatedDate).IsModified = false;
        }
    }

    return await _context.SaveChangesAsync() > 0;
}
公共虚拟异步任务插入更新(TE实体)
{
////在TE中查找IEntity的所有实例:
////*如果实体是新的,我们将状态设置为EntityState.Added(插入)
////*如果实体存在,我们将状态设置为EntityState.Modified(UPDATE)
找到的列表=FindAllInstances(实体);
foreach(已找到的资源)
{
if(entity.Id==0 | | entity.Id==ModelState.New)
{
//附加新实体
_context.Entry(entity.State=EntityState.Added;
}
其他的
{
//有时,当您想要更新分离的实体时,在尝试附加它之前(通过设置.State属性),
//您首先需要确保该实体尚未被附加和跟踪。如果是这种情况,则现有实体
//需要分离并附加更新的实体。
var attachedEntity=_context.ChangeTracker.Entries().FirstOrDefault(e=>e.Entity.Id==Entity.Id);
如果(附件身份!=null)
{
//您要更新的实体已附加,我们需要将其分离并附加更新的实体
_Entry(attachedEntity.Entity).State=EntityState.Distached;
}
_context.Entry(entity.State=EntityState.Modified;//附加实体,并将状态设置为Modified。
_context.Entry(entity).Property(o=>o.CreatedUserId).IsModified=false;
_context.Entry(entity).Property(o=>o.CreatedDate).IsModified=false;
}
}
return wait_context.SaveChangesAsync()>0;
}

您可以使用内部上下文,它是ObjectContext

var ctx = ((IObjectContextAdapter)_context).ObjectContext;
然后对所需的任何实体调用
ctx.Detach()
。幸运的是,这不是一种通用方法

您还可以从
ObjectContext
获取对
ObjectStateManager
的引用,并使用它来执行任何需要的状态更改

更多信息:


作为旁注,您不能使用
\u context.Set().Find(entity.Id)
而不是查看更改跟踪器吗?