Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

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 });
   5:  
   6:     //insert without first loading
   7:     session.Insert(new Order { Customer = new Customer { Id = 1 }, Product = new Product { Id = 1 } });
   8:  
   9:     //update without first loading
  10:     session.Update(new Order{ Id = 1, Product = new Product{ Id = 2 }})
  11: }

Bookmark and Share

Comments

Ricardo Peres said:

Darren:

Yes, I know... thanks, anyway!

# August 30, 2012 12:14 PM