How do I make modifications to a object that I don't want to commit in nhibernate?
I have ninject make a new session on httpRequest and close it at the end of the httpRequest.
Now I learned through the nhibernate profile that I should always wrap everything in a transaction even queries(read).
This has caused so many bugs now in my code because I would retrieve an object back from the database and then do modifications to that object(mostly converting the utc time to local time).
These modifications should never be committed to the database but since I am now wrapping all my read queries in a transaction what requires a commit when I go and grab something else out of the database it does a commit and it see's that my object changed an开发者_Go百科d saves the changes that should never be saved to the database.
I would use evict but then I lose lazy loading and I usually convert the times before I actually do some other queries that activate lazy loading.
What should I do?
NHibernate 3.1 has a SetReadOnly()
method on IQuery
and ICriteria
that ensures objects returned by the query will not be persisted by the session.
I suggest that you load the results of the query into a viewmodel
and then on a property of your viewmodel
convert your date into local time. Because the viewmodel
is NOT
attached to the nHibernate session then you will not update the entity when your end of httpRequest commits the transaction.
A viewmodel
is in effect a DTO
and can be described as a flattened model
of your data
See this post for more info (especially the answer regarding automapper)
edit It seems that your pain point is when the actual display of the data is performed. When I run into these problems I always use a displayFor
template. On my view I use something along then lines of:-
Please note this is a contrived example:-
<h1>Books</h1>
<ul>
@foreach (var book in Model)
{
<li>@book.Name @Html.DisplayFor(x=> book.UnitPrice, "Price")</li>
}
</ul>
And then create a display template /Views/Shared/DisplayTemplates/Price.cshtml
@model decimal
<span>£@Model</span>
Note: This view could perform your calculation via a helper etc...
This gives you quite a few benefits BUT it does mean that every where I use a price I have to use a display template. However I feel it is easier to remember that I need to use a display template for all my prices, dates etc, rather than some named helper that may get missed. It is always about training/conditioning yourself.
Its all open to debate and at the end of the day you need to feel comfortable with the way you work. However display templates seems to work better for me.
I should also point out that I urge you to think of this as a display problem and not try to provide a kludge retrieving your data from the database.
精彩评论