asp.net mvc - Why is NHibernate persisting new objects in the wrong order of creation even inside a transaction? -
in asp.net mvc app have log object tracks happens in forum. when comment added inside transaction following happens:
a new comment added submissions table
a new log entry reference id of comment added logs table
finally transaction committed , no exceptions generated. turns out when transaction committed, nhibernate first inserts log record , comment record, therefore saving log record incorrect comment id 0.
here code show happening:
using (iatomictransaction transaction = unitofwork.begintransaction()) { try { submissionrepository.addcomment(comment, parentsubmission); logrepository.addcommententry(comment); transaction.commit(); } catch { transaction.rollback(); throw; } }
unitofwork , atomictransaction wrappers around isession , itransaction objects nhibernate apis. , here log generated confirms problem:
2011-02-09 14:42:05,631 [15] debug nhibernate.sql - insert logs (version, created_at, updated_at, comment_id) values (?p0, ?p1, ?p2, ?p3); ?p0 = 9/02/2011 2:42:05 pm, ?p1 = 9/02/2011 3:41:52 am, ?p2 = null, ?p3 = 0 2011-02-09 14:42:05,647 [15] debug nhibernate.sql - select last_insert_id() 2011-02-09 14:42:05,647 [15] debug nhibernate.sql - insert submissions (version, created_at, updated_at, body) values (?p0, ?p1, ?p2, ?p3);?p0 = 9/02/2011 2:42:05 pm, ?p1 = 9/02/2011 3:41:52 am, ?p2 = 9/02/2011 3:41:52 am, ?p3 = 'dfgdfgd dfg df' 2011-02-09 14:42:05,647 [15] debug nhibernate.sql - select last_insert_id()
what solution problem?
update:
so turned out if call flush after every insert order correct.
using (iatomictransaction transaction = unitofwork.begintransaction()) { try { submissionrepository.addcomment(comment, parentsubmission); unitofwork.currentsession.flush(); logrepository.addcommententry(comment); unitofwork.currentsession.flush(); transaction.commit(); } catch { transaction.rollback(); throw; } }
sure, when try add comment , log entry in single transaction id of comment
isn't yet generated, unless use "manual id assignment" approach or flush session persist changes made.
in original post there no "flush" after add comment , want add log comment (for id isn't defined yet).
not sure why nhibernate takes such reverse order seems @ least id generation issue.
another thing caught attention use comment
, args.comment
side side. difference?
anyway, if comment
domain entity, have to:
- insert it;
- make sure attached current
isession
(you should have session-attachedcomment
entity object available); - use exatly entity (which in repository already) log entry (nhibernate take care of relations).
Comments
Post a Comment