I am working on a c# console application, and I am using entity framework 5.0 as the data access layer with sql server. now I want to track the changes and save them inside a log table. so to do so I am initiating 2 DbContext objects one for the business data while the other for the log data, as follow:
class Sync
{
static void Main(string[] args)
{
string syncResult = "Sync started";
Entities entities = new Entities();//for business data
Entities entities2 = new Entities();//for logs
try
{
//code goes here
entities.SaveChanges();
}
catch (Exception e)
{
syncResult = string.IsNullOrEmpty(e.Message) ? "Error" : e.Message;
}
entities.Dispose();
entities2.LogHistories.Add(new LogHistory() { Description = syncResult });
entities2.SaveChanges();
entities2.Dispose();
now i provided separate DbContext objects for my logs , for the following reason/s:-
- if my first entity object is not able to save the changes , due to any reason such as unhandled validation error, or trying to hack the system, etc.. then the second entities2 will still be able to save the log entry. let take this example. let say I am integrating with a 3rd part API and I am expecting them to return JSON in a specific format.. now let assume that the return json object had missing data, in this case when I try adding the object it will raise and exception ... now since I am having separate entity object for the logs then the log entry will be saved (will not be affected by any business data exception). but if I was having a single DBContext object then the log entry will fail to save since I am unable to save the business data .. so my question is if initiating 2 DBContext objects one for logs and the other for business data a valid approach to follow, or it is a bad decision to follow?