如何重构此代码以便我可以集中投影?
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 { ... } }
基本上,我在每个案例陈述中都有很多案例陈述和长期预测.我担心一旦DTO需要改变,比如添加一个新字段,其他情况的投影可能彼此不一致(忘记或错过更新).我该如何集中这个?
解决方法
你能这样接近吗?
var query = tempItems.AsQueryable(); switch(itemType) { case ItemType.Damaged: query.Join(...); break; case ItemType.Fixed: query.Where(...); } query.Select(e => new ItemDto{//Lots of properties}); return query.ToList();