NHibernate Readonly Entities at Runtime
I would like to know if there is a way to make an instance of an entity immutable at runtime. 开发者_如何学PythonI know that I can have readonly types, but I would like readonly instances of types at runtime. Reason being, that I want to use NH domain objects like a lightweight entity by modifying properties, but don't want those changes to persist when doing a Session.Flush () or similar. There is always Session.Evict(), but that won't prevent the unknowing developer from a Session.Save () on a "readonly" entity.
At runtime huh? I'm still a bit puzzled with what exactly your asking but I've done something like this in the past:
foreach (var order in orders)
{
_nhSession.SetReadOnly(order, true); //prevent database updates
}
I did this a while back because when I queried for a list of orders, some of the properties on the entity were not made nullable when they should have been. Thus when NHibernate did the flush, it was trying to update all of my orders and set the few fields that were null from the database to their default C# values such as an Integer field in the database set to NULL would change to a 0 in C#.
Take a look at this article by Fabio Maulo, you can use that as a starting point and change it to track individual entities.
精彩评论