Reputation: 431
We have an old WinForms software which we want to migrate to Asp.Net-Core. The old Database requires end user access by an ActiveDirectory user. Our Asp.Net-Core app is running with AppPool-User but the db access needs an impersonated user context.
I only want to execute db calls impersonated.
Which method I have to overwrite in the DBContext-class of EF-Core if I want to hook my custom code before SQL is send to the server?
I'm not interested in hooks which manipulates the internal ChangeTracking.
Upvotes: 0
Views: 809
Reputation: 3367
Would the override of Save itself do the trick for you?
public class MyContext : DbContext
{
public override int SaveChanges()
{
RunInpersonated();
return base.SaveChanges();
}
}
Edit: Now that I think of it again, that's only for write access, not for read, and you probably need both.
You could also implement repository pattern, and add your impersonation logic there. Also SQL for read queries is actually sent to the DB when you execute methods like ToListAsync()
on IQueryable
and fetching the results. You could write your own extension methods like ToList
, add your impersonation thing there, and than call normal ToList
method.
Upvotes: 0
Reputation: 5715
If you're using EF Core 3.0+ you can use Interceptors. Keep in mind that database interceptors are supported for relational database providers only, though. They provide you access to the typical db command operations, including connection and transaction management.
You can TAG your queries as to easily recognize them in the interceptor logic. You will find good examples for that in the Interceptors page.
Upvotes: 1