New Profiler Feature: Avoid Writes from Multiple Sessions In The Same Request
Join the DZone community and get the full member experience.
Join For Freebecause i keep getting asked, this feature is available for the following profilers:
- nhibernate profiler
- entity framework profiler
- linq to sql profiler
- llblgen profiler
- hibernate profiler
this new feature detects a very interesting bad practice, write to the database from multiple session in the same web request.
for example, consider the following code:
public void saveaccount(account account)
{
using(var session = sessionfactory.opensession())
using(session.begintransaction())
{
session.saveorupdate(account);
session.transaction.commit();
}
}
public account getaccount(int id)
{
using(var session = sessionfactory.opensession())
{
return session.get<account>(id);
}
}
it is bad for several reasons, micro managing the session is just one of them, but the worst part is yet to come…
public void makepayment(int fromaccount, int toaccount, decimal ammount)
{
var from = dao.getaccount(fromaccount);
var to = dao.getaccount(toaccount);
from.total -= amount;
to.total += amount;
dao.saveaccount(from);
dao.saveaccount(to);
}
do you see the error here? there are actually several, let me count them:
- we are using 4 different connections to the database in a single method.
- we don’t have transactional safety!!!!
think about it, if the server crashed between the fifth and sixth lines of this method, where would we be?
we would be in that wonderful land where money disappear into thin air and we stare at that lovely lawsuit folder and then jump from a high window to a stormy sea.
or, of course, you could use the profiler, which will tell you that you are doing something which should be avoided:
isn’t that better than swimming with the sharks?
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments