How do I refactor this code so I can centralize the projection?
public IEnumerable<ItemDto> GetItemsByType(int itemId, ItemType itemType)
{
IEnumerable<ItemDto> items = null;
try
{
var tempItems= _Items.Get(i => i.ItemId == itemId
&& o.Active == true);
switch (itemType)
{
case ItemType.Normal:
items = from item in tempItems
select new ItemDto
{
// many fields here
};
break;
case ItemType.Damaged:
items = from item in tempItems
join itemDetail in _ItemDetails.Get() on item.ID equals itemDetail.ItemID
select new ItemDto
{
// many fields here
};
break;
case ItemType.Fixed:
items = from item in tempItems
join itemDetail in _ItemDetails.Get() on item.ID equals itemDetail.ItemID
where item.Status.ToLower() == "fixed"
select new ItemDto
{
// many fields here
};
break;
// more case statements here...
default:
break;
}
}
catch { ... }
}
Basically, I have lots of case statements and a long projection on each case statement. I'm worried that once the DTO needs to change, say add a new field, the other cases' projection might not be consistent with each other (forgot or missed updating). How can I centralize this?
You could do something like this:
var baseQuery = from item in tempItems select item;
switch (itemType)
{
case ItemType.Fixed:
baseQuery = from item in baseQuery where item.ID equals itemID select item;
break;
}
return (from item in baseQuery select new ItemDTO (...projection here... ));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With