Question

In a lot of apps I write, I find myself assigning a default value for a subclass of a DBML object. Here is an example of the current way I'm having to do it:

var viewModel = new RandomViewModel
{
    ContactName = (Order.Customer != null ? Order.Customer.ContactName : "Unknown"),
    Date = Order.OrderDate,
    Shipper = (Order.Shipper != null ? Order.Shipper.CompanyName : "Fedex"),
    ShipCity = Order.ShipCity,
    ShipRegion = Order.ShipRegion,
    FirstCategory = (Order.OrderDetails.First().Product.Category != null
        ? Order.OrderDetails.First().Product.Category.CategoryName
        : "DefaultCategory",
    ItemCount = Order.OrderDetails.Count
};

Ideally it would be most readable as this:

var viewModel = new RandomViewModel
{
    ContactName = Order.Customer.ContactName ?? "Unknown",
    Date = Order.OrderDate,
    Shipper = Order.Shipper.CompanyName ?? "Fedex",
    ShipCity = Order.ShipCity,
    ShipRegion = Order.ShipRegion,
    FirstCategory =
        Order.OrderDetails.First().Product.Category.CategoryName
        ?? "DefaultCategory",
    ItemCount = Order.OrderDetails.Count
};

but there is a NullReferenceException for any foreign keyed object that is null. I don't think null coalescing is usable here, but is there some other consise way to accomplish this very frequent task? Perhaps with a class/method extension, or even a VS macro?

I used the Northwind database for this example:

northwind db

Open to any and all suggestions.

Was it helpful?

Solution

Here's one possible approach to take. Declare partial class Order, with properties like this:

string CustomerNameOrDefault { get { return Customer != null ? Customer.ContactName : "Unknown"; } }

Then your code becomes:

var viewModel = new RandomViewModel
{
    ContactName = Order.CustomerNameOrDefault,
...

OTHER TIPS

Open to any and all suggestions.

Personally I use AutoMapper to map between my domain models and view models. Your code could now become:

RandomViewModel viewModel = Mapper.Map<Order, RandomViewModel>(Order);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top