null object exceptions

May 19, 2010 at 11:27 AM
I was just curious if anyone had any suggestions for dealing with null objects when the database is empty. For example, let's say I have customers and sales reps, such that I have nHydrate code that looks like this to get the sales rep's name for a customer: Customer.SalesRepItem.Name If I haven't assigned a sales rep to that customer yet, the SalesRep object comes back as null and I'd get an error trying to traverse down to Name. My solution so far has been clunky: if (Customer.SalesRepItem != null) { something.Text = Customer.SalesRepItem.Name } I'd be content if nHydrate gave me a blank shell of SalesRep, but instead it returns a null object. I'm working with a couple hundred tables, all with several relationships, and I'm gonna end up having a gazillion of these little if statements unless someone's got a better idea. I'm hoping I'm overlooking something simple. Thanks.
Coordinator
May 22, 2010 at 9:05 PM

This is correct and by design. If you have a nullable field on which there is a relationship to another table then the object can be null too. Since this is all business rule based, you will need to write the code to satisfy your business rule. In your case the fact that there is no SalesRep is a perfectly valid situation. In another business, they might have allow 0 or 1 SalesReps so the linking field is nullable. In your situation, it seems that you can never have a nullable SalesRep object. In that case make your SalesRepId (or whatever the field is called) to non-nullable and actually add it at the time of Customer add. This is a business rule and should be handled as such.