NHibernate Pitfalls: Private Setter on Id Property

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

Having a private setter on an entity’s id property may seem tempting: in most cases, unless you are using id generators assigned or foreign, you never have to set its value directly.

However, keep this in mind:

  • If your entity is lazy and you want to prevent people from setting its value, make the setter protected instead of private, because it will need to be accessed from subclasses of your entity (generated by NHibernate);
  • If you use stateless sessions, you can perform some operations which, on regular sessions, require you to load an entity, without doing so, for example:
   1: using (IStatelessSession session = factory.OpenStatelessSession())
   2: {
   3:     //delete without first loading
   4:     session.Delete(new Customer { Id = 1 });
   6:     //insert without first loading
   7:     session.Insert(new Order { Customer = new Customer { Id = 1 }, Product = new Product { Id = 1 } });
   9:     //update without first loading
  10:     session.Update(new Order{ Id = 1, Product = new Product{ Id = 2 }})
  11: }

Bookmark and Share


1 Comment

Comments have been disabled for this content.