NHibernate Pitfalls: Private Setter on Id Property
- by Ricardo Peres
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: }