반응형
엔티티가 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();
반응형
'IT Share you' 카테고리의 다른 글
ByteArrayOutputStream을 닫아도 효과가 없습니까? (0) | 2021.01.07 |
---|---|
node.js로 기본 Ajax 보내기 / 받기 (0) | 2021.01.07 |
"연결 실패 : 사용자 'root'@ 'localhost'에 대한 액세스가 거부되었습니다 (암호 사용 : YES)"PHP 함수에서 (0) | 2021.01.07 |
JSON.stringify 반환 [] (0) | 2021.01.07 |
/ dev / tty의 특별한 점은 무엇입니까? (0) | 2021.01.07 |