Click here to Skip to main content
15,888,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using EF4.2 and Code First (although I've had to deal with this sine Linq2SQL), I find myself coming across situations like this all the time:

C#
Label1.Text = MyEvent.EventType.Description;


MyEvent is of type Event, and EventType is a navigation property.

This works great unless the EventType is null, because it hasn't been defined yet. This is part of a form that is filled out over time so many fields and related properties will be null during the process.

At first, I'd write:

C#
Label1.Text = MyEvent.EventType == null ?? "" : MyEvent.EventType.Description;


This works, but does it make an inelegant mess out of my app code (and it's a lot of typing, too).

It was suggested to me that I should put some logic in the Getter but I'm not sure how Code First will handle that and I'd like to avoid making a mess out of my class definitions by blowing them up with private backing variables and full-length property definitions (currently using auto-properties which makes things very neat and readable).

My current solution to this problem is to define an extension method on the EventType like so:

C#
public static string GetDescription(this EventType ThisEventType)
{
    return (ThisEventType == null ? "" : ThisEventType.Description);
}


so that I can:

C#
Label1.Text = MyEvent.EventType.GetDescription();


It's clean but the redundancy of .Description and .GetDescription bothers me since it's just asking to be the kind of bug where using .Description compiles nice and tests out fine in Dev/Test but may blow up in production later when a null rolls through and someone forgot to use .GetDescription.

I've thought about using reflection and property names in strings but that's so asp/ado!

Does anyone else have a nice, clean (and better!) solution to this problem? This is such a common scenario, there should be a nice way to handle it.
Posted

1 solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900