Mohammad
Mohammad

Reputation: 1588

Entity Framework Core 2.1, ChangeTracker.Tracked

I'm trying to figure out how to use Entity Framework Cores 2.1 new ChangeTracker.Tracked Event to hook into reading queries. Unfortunately, I'm not being able to understand how to implement this. Since it's a new feature it's not possible to find any articles on it and the official Microsoft docs site does not provide any help or sample code. My scenario is pretty simple. I have a database with following columns: id, customerId, metadata. When a user queries this table I want to intercept the query result set and for every row, I want to compare the customerId with currently logged in user. I'm hoping that ChangeTracker.Tracked Event can help me in intercepting the return result set. I'm looking for some sample code on how to achieve above.

Upvotes: 3

Views: 2620

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205539

Here is a sample usage of the ChangeTracker.Tracked event.

Add the following method to your context (requires using Microsoft.EntityFrameworkCore.ChangeTracking;):

void OnEntityTracked(object sender, EntityTrackedEventArgs e)
{
    if (e.FromQuery && e.Entry.Entity is YourEntityClass)
    {
        var entity = (YourEntityClass)e.Entry.Entity;
        bool isCurrentUser = entity.customerId == CurrentUserId;
            // do something (not sure what)
    }
}

and attach it to the ChangeTracker.Tracked even in your context constructor:

ChangeTracker.Tracked += OnEntityTracked;

As described in the Tracked event documentation:

An event fired when an entity is tracked by the context, either because it was returned from a tracking query, or because it was attached or added to the context.

Some things to mention.

  • The event is not fired for no-tracking queries

  • The event is fired for each entity instance created by the tracking query result set and not already tracked by the context

  • The bool FromQuery property of the event args is used to distinguish if the event is fired from the tracking query materialization process or via user code (Attach, Add etc. calls).

  • The EntityEntry Entry property of the event args gives you access to the entity instance and other related information (basically the same information that you get when calling the non-generic DbContext.Entry method)

Upvotes: 12

Related Questions