ObjectStateManager.ObjectStateManagerChanged in Entity Framework Core

天涯浪子 提交于 2019-12-19 09:01:43

问题


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 notified whenever an entity is loaded into the context.


回答1:


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.



来源:https://stackoverflow.com/questions/45132553/objectstatemanager-objectstatemanagerchanged-in-entity-framework-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!