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.
DbContext should not be used as a singleton because it is holding a connection object which cannot be used by multiple threads at the same time.
EF and EF Core DbContext types implement IDisposable . As such, best practice programming suggests that you should wrap them in a using() block (or new C# 8 using statement). Unfortunately, doing this, at least in web apps, is generally a bad idea.
A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.
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:
class UserLogin
{
private TempDBEntity dbContex;
UserLogin()
{
// ctor create dbContext
}
void Login()
{
// Login...
}
void AddLog()
{
// ...
}
void SaveChanges()
{
//dbContext.SaveChanges()...
}
}
Passing a dbcontext as parameter is in my point of view not a very good solution. But this is opinion based...
You can use the dbcontext as follows:
Action: Login
using(TempDBEntity context = new TempDBEntity())
{
var temp = context.Users.Where(m => m.user_unique_id == 1).FirstOrDefault();
temp.timestamp = new DateTime();
temp.AddLog("Login", context);
}
Function: AddLog
public void AddLog(string activity, TempDBEntity context)
{
var log = new UserLog();
log.user_id = this.user_id;
log.activity = activity;
context.UserLog.Add(log);
context.SaveChanges();
}
This will properly dispose the object after its use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With