Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework multiple contexts for logging

I've seen a fair few articles/posts that recommend not having more than one context per request when using EF.

Is it valid to have a second context for logging purposes such as 'user x did y', 'failed login from z' etc.

The rationale behind this is that I'd like these errors to be logged even if there is an error while using the "main" context, ie. foreign key issues etc.

Is there another way to do this or if I head down this road is there any things to try and avoid?

like image 777
Daniel Powell Avatar asked May 22 '26 11:05

Daniel Powell


1 Answers

You can always have more context instances if your application logic really needs them and ability to persist log to database even with invalid data in the main context can be considered as such situation. You just need to ensure that your updates do not run in the same transaction (they must use different DB connection as well) - that should be a default behavior unless you use TransactionScope.

like image 96
Ladislav Mrnka Avatar answered May 24 '26 17:05

Ladislav Mrnka