NHibernate. Field update only on first save
How can I开发者_JS百科 make NHibernate to update any field ONLY on first saving and not to update it on session.Update(obj)
?
EDIT: For example, I have an entity A
, that has reference to entity B
, like:
public class A
{
// ... some properties
public virtual B PropB {get; set;}
}
After retrieving the instance of class A
I save all its properties instead of PropB
into fields on web page (including id and version). After user modified some fields and click 'Save' (herewith I am sure, that he can not edit PropB
), I can just restore this object from the web page and save it to the database but I can not restore the linked PropB
. So, when I save A
instance, it looses link. So, because of PropB
can not be modified by any way after first saving, I need a solution to restrict its updating.
There's a mapping attribute that effectively makes a property insert-only: update="false"
.
However, there are two issues with your question:
session.Update
does not update an entity, flushing the session does. You only need to callsession.Update
to attach entities that were not loaded by the session.- Why are you modifying a property you don't intend to update in the DB?
I would us DTO's in this case and update the entities within the transaction.
Pseudo-code:
public StoreB(ADto dto)
{
using (transaction)
{
A entity = session.Get<A>(dto.Id);
entity.PropB = dto.PropB;
transaction.Commit();
}
}
public StoreC(ADto dto)
{
using (transaction)
{
A entity = session.Get<A>(dto.Id);
entity.PropC = dto.PropC;
transaction.Commit();
}
}
精彩评论