How to refresh an Entity Framework Core DBContext?

前端 未结 5 1576
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 01:58

When my table is updated by another party, the db context in dotnet core still return the old value, how can I force the Db context to refresh?

I\'ve done research b

5条回答
  •  一个人的身影
    2020-12-10 02:28

    Here is my solution, I hope it will help you.

    • The detach function will detach all nested entities and array of entities.
    • The findByIdAsync will have an optional parameter to detach the entity and will reload it.

    Repository

        public void Detach(TEntity entity)
        {
            foreach (var entry in _ctx.Entry(entity).Navigations)
            {
                if (entry.CurrentValue is IEnumerable children)
                {
                    foreach (var child in children)
                    {
                        _ctx.Entry(child).State = EntityState.Detached;
                    }
                }
                else if (entry.CurrentValue is IEntity child)
                {
                    _ctx.Entry(child).State = EntityState.Detached;
                }
            }
            _ctx.Entry(entity).State = EntityState.Detached;
        }
    

    So for exemple with:

    Classes:

    public interface IEntity
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        TPrimaryKey Id { get; set; }
    }
    
    public class Sample : IEntity
    {
        public Guid Id { get; set; }
        public string Text { get; private set; }   
        public Guid? CreatedByUserId { get; set; }
        public virtual User CreatedByUser { get; set; }     
        public List SampleItems { get; set; } = new List();
    }
    
    public class SampleItem : IEntity
    {
        public Guid Id { get; set; }
        public string Text { get; private set; }   
        public Guid? CreatedByUserId { get; set; }
        public virtual User CreatedByUser { get; set; }     
    }
    

    Manager

        public async Task FindByIdAsync(Guid id, bool includeDeleted = false, bool forceRefresh = false)
        {
            var result = await GetAll()
                .Include(s => s.SampleItems)
                .IgnoreQueryFilters(includeDeleted)
                .FirstOrDefaultAsync(s => s.Id == id);
    
            if (forceRefresh)
            {
                _sampleRepository.Detach(result);
                return await FindByIdAsync(id, includeDeleted);
            }
    
            return result;
        }
    

    Controller

        SampleManager.FindByIdAsync(id, forceRefresh: true);
    

提交回复
热议问题