Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning specifically shaped POCOs to ASP.NET MVC actions

In my ASP.NET MVC project, my actions typically call a Service layer to get data. I use the same dozen or so POCOs for all my models. I also plan on using the Service layer in console applications and maybe expose a web api at some point.

To make my database operations more efficient, my service layer only hydrates the properties in the model that are relevant to the particular method (which at this point is mostly driven by the needs of my controller actions).

So for example I might have a class Order with properties Id, Name, Description, Amount, Items. For a given service call I might only need to populate Id, Name, Items. A consumer of that service won't necessarily know that Amount is 0 only because it didn't populate the property.

Similarly, the consumer won't know whether Items is empty b/c there actually aren't any items, or whether this particular service method just doesn't populate that property.

And for a third example, say one of my views displays an ItemCount. I don't want to fully populate my Items collection, I just need an additional property on my "model". I don't want to add this property to my POCO that other service methods will be using because it's not going to be populated anywhere else.

So the natural solution is to make a POCO designed specifically for that method with only those 3 properties. That way the consumer can know that all properties will be populated with its real values. The downside to this is that I'll end writing tons of similarly shaped models.

Any advice on which method works best?

like image 781
kenwarner Avatar asked Jan 24 '12 17:01

kenwarner


1 Answers

You could use Nullable Types to indicate the missing properties with a null.

For example:

class Order {
    public int Id {get;set;}
    public string Name {get;set;}
    public string Description {get;set;}
    public decimal? Amount {get;set;}
    public List<Item> Items {get;set;}
}

And then if Items == null, it wasn't set. If it's an empty new List<Item>(), it's set but empty. Same for Amount. If Amount.HasValue == false, it wasn't set. If Amount.Value is 0.0d, it's set and the item is free.

like image 194
sblom Avatar answered Sep 21 '22 19:09

sblom