简体   繁体   中英

What is the best way to audit reading of entities with LinQ in EF6?

I have a code-first EF database setup which is accessed with an OData controller from the front end.

I am trying to audit the entities that the user loads.

How can I intercept the materialized entities after LinQ execution?

For example:

var entity = _service.Queryable().FirstOrDefault(x => x.ID == key);

I want to add a custom action after the entity is materialized and have access to it.

I've tried to use the DbContext.Database.Log, but I get only the EF generated queries.

The solution was actually simple.

Since I only wanted to log user requests from frontend, I extended the OData controller to add audit logs whenever an entity was requested.

This way, no matter what LinQ filtering is done in the backend, I get access to the result of the user request:

var entity = _service.Queryable().Where(x => x.ID == key);
Logger.AddAuditLog(entity);
//... continue execution

Hope this helps someone!

Here is a way to do it with the ObjectMaterialized event

using (var context = new EntityContext())
{
    // could be set globally in the constructor
    var materialized = new List<object>();
    ((IObjectContextAdapter) context).ObjectContext.ObjectMaterialized += (sender, args) => materialized.Add(args.Entity);

    var list = context.Customers.ToList();

    FiddleHelper.WriteTable(materialized);      
}

Online Example: https://dotnetfiddle.net/yzmlSO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM