nhibernate: how to setup entity validation that uses data from database? -
i've setup nhibernate have problems validating entity before actual save , commit database. load , change persistent entity, validation goes after accessing database , doing commiting transaction, saving entity in database before actual validation result known.
i use repository pattern in .net mvc web app , goes this:
public actionresult edit(int id, entity entity) { var repository = new entityrepository(); // persistent entity nhibernate var entityoriginal = repository.getbyid(id); // copy data input entity persistent entity entity.copydatatoentity(entityoriginal); // if validation ok save database // validations problematic becouse needs info database , uses transaction validationresult validationresult = entityoriginal.validate(); if (validationresult.isvalid()) { repository.save(entityoriginal); // ok, redirect view entity page return redirecttoaction("view"); } else { repository.evict(pratecilist); foreach (var message in validationresult.errormessages) { modelstate.addmodelerror(message.key, message.value); } return redirecttoaction("pogledaj"); } }
update: clarification ok here's code:
// persistent entity nhibernate var entityoriginal = repository.getbyid(id); entity.copydatatoentity(entityoriginal); validationresult validationresult = entityoriginal.validate();
- i persistent entity database
- i change it... if session flushed persisted in database
- i entity.validate() gets entity database , commits in process (as have commit fetching database)!... entity try validate persisted in database during validation itself.
so problem entity.validate() check database correctly inputed data, , since transaction commited on session.get(), changed entity saved (valid or invalid) right there.
my repository implementation classic:
public virtual bool save(t entity) { var session = sessionprovider.getrequestsession(this.databasename); using (var transaction = session.begintransaction()) { try { session.saveorupdate(entity); transaction.commit(); } catch (exception ex) { _log.error("could not save object database.", ex); if (transaction.isactive) { transaction.rollback(); } session.close(); return false; } } return true; }
how can achieve validation can check stuff in database?
possible solution validate before make changes persistent object, such pain there must better way. thank help.
the solution i've found ugly works:
- get original entity database
- clone (copy every data) new instance
- modify , validate new instance
- if validation ok, copy new instance original , save
still looking better solution though.
Comments
Post a Comment