ObjectStateManager.ObjectStateManagerChanged in Entity Framework Core

后端 未结 1 1913
误落风尘
误落风尘 2021-01-13 05:46

I can\'t seem to find ObjectStateManager.ObjectStateManagerChanged in ef core. Has this been removed and if so what is the alternative?

I want to be not

相关标签:
1条回答
  • 2021-01-13 06:02

    Currently (the latest official EF Core v1.1.2) there is no public alternative. There are plans to expose Lifetime Hooks, but according to EF Core Roadmap they are postponed and will not be available in the upcoming v2.0 release.

    Luckily EF Core exposes all the internal infrastructure classes/interfaces, so I could suggest the following workaround under the typical EF Core internals usage disclaimer

    This API supports the Entity Framework Core infrastructure and is not intended to be used directly from your code. This API may change or be removed in future releases.

    What I have in mind is utilizing the Microsoft.EntityFrameworkCore.ChangeTracking.Internal namespace, and more specifically the ILocalViewListener interface which provides the following method

    void RegisterView(Action<InternalEntityEntry, EntityState> viewAction)
    

    The viewAction allows you to register delegate which will be called on any entity state change, including attaching, adding, deleting, detaching etc.

    So inside your DbContext derived class constructor, you could obtain ILocalViewListener service and register the handler like this:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
    using Microsoft.EntityFrameworkCore.Infrastructure;
    
    public class MyDbContext : DbContext
    {
        // ...
        public MyDbContext()
        {
            this.GetService<ILocalViewListener>()?.RegisterView(OnStateManagerChanged);
        }
    
        void OnStateManagerChanged(InternalEntityEntry entry, EntityState previousState)
        {
            if (previousState == EntityState.Detached && entry.EntityState == EntityState.Unchanged)
            {
                // Process loaded entity
                var entity = entry.Entity;
            }
        }
    }
    

    Inside the handler, you can also use the InternalEntityEntry.ToEntityEntry() method to get the regular EntityEntry object (similar to DbContext.Entry and ChangeTracker.Entries methods) if you prefer working with it rather than the internal InternalEntityEntry class.

    Tested and working in EF Core v1.1.2.

    0 讨论(0)
提交回复
热议问题