Prevent setting a property value after already been set
We want Nhibernate to do whatever it needs. But we also want to limit the application programmer from doing crazy things, for example: Setting the Unique Identifier of an existing entity to another value. I know it sounds crazy but in a medium-sized team, anything can happen and this stuff is critical for the future.
So I thought about a very KIS way to implement this kind of protection.
* What I write here is the most readable version of my code, you can extract method, use interceptor, AOP, whatever works for you.
private long _id;
public long ID
{
get { return _id; }
set
{
if (!_id.Equals(default(long)) && !_id.Equals(value))
{
throw new InvalidOperationException(
"You can't set this property, it has already been set");
}
_id = value;
}
}
Very simple, easy to test, and it works with NHibernate proxy.
Comments