IT Share you

엔티티가 dbContext에 연결되었는지 여부를 확인하는 가장 합리적인 방법은 무엇입니까?

shareyou 2021. 1. 7. 19:57
반응형

엔티티가 dbContext에 연결되었는지 여부를 확인하는 가장 합리적인 방법은 무엇입니까?


엔티티를 컨텍스트에 연결하려고하면 예외가 발생합니다.

동일한 키를 가진 개체가 ObjectStateManager에 이미 있습니다. ObjectStateManager는 동일한 키로 여러 개체를 추적 할 수 없습니다.

이것은 예상되는 동작입니다.

하지만 ObjectStateManager가 어떻게 알고 있는지 알고 싶습니다. 전에 혼자서 확인하고 싶습니다


DbContext API를 사용하는 경우 (ef-code-first에 대해 언급 했음) 다음을 간단히 사용할 수 있습니다.

context.YourEntities.Local.Any(e => e.Id == id);

또는 더 복잡한

context.ChangeTracker.Entries<YourEntity>().Any(e => e.Entity.Id == id);

ObjectContext API의 경우 다음을 사용할 수 있습니다.

context.ObjectStateManager.GetObjectStateEntries(~EntityState.Detached)
                          .Where(e => !e.IsRelationship)
                          .Select(e => e.Entity)
                          .OfType<YourEntity>()
                          .Any(x => x.Id == id);

다음은 이미 첨부되었는지 여부에 대해 걱정할 필요없이 컨텍스트에서 객체를 가져 오는 확장 메서드입니다.

public static T GetLocalOrAttach<T>(this DbSet<T> collection, Func<T, bool> searchLocalQuery, Func<T> getAttachItem) where T : class
{
    T localEntity = collection.Local.FirstOrDefault(searchLocalQuery);

    if (localEntity == null)
    {
        localEntity = getAttachItem();
        collection.Attach(localEntity);
    }

    return localEntity;
}

전화 :

UserProfile user = dbContext.UserProfiles.GetLocalOrAttach<UserProfile>(u => u.UserId == userId, () => new UserProfile { UserId = userId });

검사

entity.EntityState == System.Data.EntityState.Detached

부착하기 전에


참고 경우 그 변경 내용 추적이 묻는 당신의 상황에 사용할 수있는 ObjectStateManager또는 ChangeTracker개체가 아니라고 힘 리턴 ObjectContext거기에 이미 사실 인 경우에도. 따라서 이러한 객체를 첨부하려고하면 예외가 발생합니다.

context.Set<T>.Local.Any(e => e.Id == id);

변경 내용 추적이 비활성화 된 경우 이벤트를 작동합니다.

객체의 유형을 모르는 경우 반사 또는 이와 같은 다른 기술을 사용하여 방법을 정의하는 다양한 접근 방식이 있습니다. int GetIdOf(object entity){...}

또는 다음과 같이 클래스에서 사용하는 인터페이스를 정의합니다.

public interface IMyEntity
{
    int Id{get;set;}
}

다음과 같이 사용하십시오.

context.Set(e.GetType()).Local.Cast<IMyEntity>().Any(e => e.Id == id);

"Any"확장 메서드를 사용하여 dbContext를 쿼리 할 수 ​​있습니다.

bool alreadyInDB = dbContext.Entity.Where(a=>a.ID==myEntity.id).Any();

참조 URL : https://stackoverflow.com/questions/6033390/what-is-the-most-reasonable-way-to-find-out-if-entity-is-attached-to-dbcontext-o

반응형