IT박스

Entity Framework 새로 고침 컨텍스트?

itboxs 2020. 9. 16. 07:29
반응형

Entity Framework 새로 고침 컨텍스트?


컨텍스트를 새로 고치려면 어떻게해야합니까? 내 데이터베이스의 뷰를 기반으로하는 엔터티가 있고 뷰에 대한 탐색 속성이있는 하나의 테이블 엔터티를 업데이트 할 때 엔터티가 업데이트되지만 뷰가 새 업데이트에 따라 새로 고쳐지지 않습니다. Db 데이터. 감사!


컨텍스트에서 항목을 새로 고치는 가장 좋은 방법은 컨텍스트를 삭제하고 새 항목을 만드는 것입니다.

당신이 경우 정말 일부 개체를 새로 고쳐야하고 DbContext 클래스와 코드 첫 번째 접근 방식을 사용하고, 당신은 사용할 수 있습니다

    public static void ReloadEntity<TEntity>(
        this DbContext context, 
        TEntity entity)
        where TEntity : class
    {
        context.Entry(entity).Reload();
    }

컬렉션 탐색 속성을 다시로드하려면 다음을 사용할 수 있습니다.

    public static void ReloadNavigationProperty<TEntity, TElement>(
        this DbContext context, 
        TEntity entity, 
        Expression<Func<TEntity, ICollection<TElement>>> navigationProperty)
        where TEntity : class
        where TElement : class
    {
        context.Entry(entity).Collection<TElement>(navigationProperty).Query();
    }

참조 : https://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbentityentry.reload(v=vs.113).aspx#M:System.Data.Entity.Infrastructure.DbEntityEntry .Reload


yourContext.Entry(yourEntity).Reload();

DbContextApi를 사용하여 특정 엔터티를 다시로드하려면 RX_DID_RX가 이미 답변을 제공했습니다.

로드 한 모든 엔티티를 다시로드 / 새로 고침하려면 다음을 수행하십시오.

Entity Framework 4.1 이상 (아마도 EF5 또는 EF 6)을 사용하는 경우 DbContext API :

public void RefreshAll()
{
     foreach (var entity in ctx.ChangeTracker.Entries())
     {
           entity.Reload();
     }
}

entityFramework 4 (ObjectContext API)를 사용하는 경우 :

public void RefreshAll()
{
     // Get all objects in statemanager with entityKey
     // (context.Refresh will throw an exception otherwise)
     var refreshableObjects = (from entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted
                                               | EntityState.Modified
                                               | EntityState.Unchanged)
                                      where entry.EntityKey != null
                                      select entry.Entity);

     context.Refresh(RefreshMode.StoreWins, refreshableObjects);
}

어쨌든 가장 좋은 조언은 "짧은 맥락"을 사용하는 것입니다. 그러면 이런 종류의 문제를 피할 수 있습니다.

이 문제에 대해 몇 가지 기사를 썼습니다.

https://christianarg.wordpress.com/2013/06/13/entityframework-refreshall-loaded-entities-from-database/


새로 고침 방법을 사용하십시오 .

context.Refresh(RefreshMode.StoreWins, yourEntity);

또는 대안으로 현재 컨텍스트를 처리하고 새 컨텍스트를 만듭니다.


context.Reload ()는 MVC 4, EF 5에서 나를 위해 작동하지 않았으므로 이것을했습니다.

context.Entry(entity).State = EntityState.Detached;
entity = context.Find(entity.ID);

잘 작동합니다.


Refreshing db context with Reload is not recommended way due to performance loses. It is good enough and the best practice to initialize a new instance of the dbcontext before each operation executed. It also provide you a refreshed up to date context for each operation.

using (YourContext ctx = new YourContext())
{
   //Your operations
}

EF 6

In my scenario, Entity Framework was not picking up the newly updated data. The reason might be the data was updated outside of its scope. Refreshing data after fetching resolved my issue.

private void RefreshData(DBEntity entity)
{
    if (entity == null) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entity);
}

private void RefreshData(List<DBEntity> entities)
{
    if (entities == null || entities.Count == 0) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entities);
}

I've made my own head hurt over nothing! The Answer was very simple- I just went back to the basics...

some_Entities   e2 = new some_Entities(); //your entity.

add this line below after you update/delete - you're re-loading your entity-no fancy system methods.

e2 = new some_Entities(); //reset.

참고URL : https://stackoverflow.com/questions/20270599/entity-framework-refresh-context

반응형