NHibernate: How to process an entity based on validation using a template for each request without having controllers aware of ISession

What is the best way to check based on an entity (each entity class has a method IsValid()that checks its internal elements) in ASP.NET MVC with a session-by-request model, where the controller has zero (or limited) knowledge of ISession ? Here is the template I am using:

  • Get the object by identifier using IFooRepository, which ends the current NH session. This returns an instance of the connected object.

  • Load an object with potentially invalid data coming from a form message.

  • Confirm the object by calling its method IsValid().

  • If the value is valid, call IFooRepository.Save(entity)that delegates the value ISession.Save(). Otherwise, an error message is displayed.

Currently, the session is open when the request begins, and cleared when the request ends . Since my object is connected to the session, session cleanup attempts to save the changes, even if the object is invalid.

What is the best way to keep validation logic in an entity class, limit knowledge to the NH controller, and avoid saving invalid changes at the end of the query?


Option 1: Explicit eviction with a validation error is implicitly cleared : if the validation fails, I can manually output an invalid object in the action method. If successful, I do nothing, and the session is automatically cleared.

Con: ( " .Save(), ?" )

2: , . , , . , , SaveChanges() , , , .

Pro: , [ 1]

Con: IRepository.Save(entity) ' SaveChanges().

3. .. / Repo.Save() .

Pro: , , NH.

Con: , NH?

+3
3

1 . , NH. , NH, , , . Evict , , .

, Manual Commit FlushMode.

+2

IsValid ( - ), , , ValidationFailed. , flush, RequestEnd. , RequestEnd, ValidationFailed - ValidationFailed, , , .
, 2!

0

/, (, , ) , . NH , , . , .

4: ,

, NH + Repositories , , Active-Record-DAL. , , NH, , .

UnitOfWork, ITransaction , , HttpRequest. , TransactionScope, :

using (var tx = new UnitOfWork()) {
    var entity = FooRepository.GetById(x);
    entity.Title = "Potentially Invalid Data";

    if (!entity.IsValid()) {
        tx.DiscardChanges();
        return View("ReloadTheCurrentView");
    }
    else {
        tx.Success();
        return RedirectToAction("Success");
    }
}

tx.DiscardChanges() , , TransactionScope, , , , .

NH Greenfield 1, . , 4 - NH , .

0

Source: https://habr.com/ru/post/1735969/


All Articles