When I call a method that need dbcontext
for update
or insert
but only want one saveChange()
like following
Action: Login
TempDBEntity context = new TempDBEntity();
var temp = context.Users.Where(m => m.user_unique_id == 1).FirstOrDefault();
temp.timestamp = new DateTime();
temp.AddLog("Login");
context.SaveChanges();
Function: AddLog
public void AddLog(string activity){
TempDBEntity context2 = new TempDBEntity();
var log = new UserLog();
log.user_id = this.user_id;
log.activity = activity;
context2.UserLog.Add(log);
context2.SaveChanges();
}
As you can see, there is double SaveChanges()
which I only need 1 SaveChanges()
.
Should I pass DBContext
as another parameter for AddLog()
or should I declare static variable for dbcontext
in this case?
Thanks a lot.
You can use the dbcontext as follows:
Action: Login
Function: AddLog
This will properly dispose the object after its use.
In your case i would create a new dabtase context in the method you need it, because this is the easiest way and you can reuse your methods very good.
This should not make a lot of performance problems, because entity framework cache all important information over the database context, so creating a new one is very fast.
If you want optimize the amount of transactions, than i would write a kind of handler, which implements it's own
SaveChanges
method and hold one databse context per instance. Than you have one more abstraction layer and a nice API for later use.Here is a simple example:
Passing a dbcontext as parameter is in my point of view not a very good solution. But this is opinion based...