.NET应用架构设计—用户端的防腐层作用及设计(5)
来源:未知 责任编辑:责任编辑 发表时间:2015-05-17 16:44 点击:次
产品类型中的一些信息主要是用来作为订单条目展现时能够更加的人性化一点,你只给一个产品ID,不能够让用户知道是哪个具体的商品。
我们接着看一个随着业务变化带来的代码急速膨胀的例子,该例子中我们需要根据OrderItem中的Pid获取Product完整信息。
using OrderManager.Port.Component;
using OrderManager.Port.Models;
using System.Collections.Generic;
using System.Web.Http;
using System.Linq;
namespace OrderManager.Port.Controllers
{
public class OrderController : ApiController
{
private readonly IOrderServiceClient orderServiceClient;
private readonly IProductServiceClient productServiceClient;
public OrderController(IOrderServiceClient orderServiceClient, IProductServiceClient productServiceClient)
{
this.orderServiceClient = orderServiceClient;
this.productServiceClient = productServiceClient;
}
[HttpGet]
public OrderViewModel GetOrderById(long oId)
{
var order = orderServiceClient.GetOrderByOid(oId);
if (order == null && order.Items != null && order.Items.Count > 0) return null;
var result = new OrderViewModel()
{
OId = order.OId,
Address = order.Address,
OName = order.OName,
Items = new System.Collections.Generic.List<OrderItem>()
};
if (order.Items.Count == 1)
{
var product = productServiceClient.GetProductByPid(order.Items[0].Pid);//调用单个获取商品接口
if (product != null)
{
result.Items.Add(ConvertOrderItem(order.Items[0], product));
}
}
else
{
List<long> pids = (from item in order.Items select item.Pid).ToList();
var products = productServiceClient.GetProductsByIds(pids);//调用批量获取商品接口
if (products != null)
{
result.Items = ConvertOrderItems(products, order.Items);//批量转换OrderItem类型
}
}
return result;
}
private static OrderItem ConvertOrderItem(OrderService.OrderItem orderItem, ProductService.Contract.Product product)
{
if (product == null) return null;
return new OrderItem()
{
Number = orderItem.Number,
OitemId = orderItem.OitemId,
Pid = orderItem.Pid,
Price = orderItem.Price,
Product = new Product()
{
Pid = product.Pid,
PName = product.PName,
PGroup = product.PGroup,
Production = product.Production
}
};
}
private static List<OrderItem> ConvertOrderItems(List<ProductService.Contract.Product> products, List<OrderService.OrderItem> orderItems)
{
var result = new List<OrderItem>();
orderItems.ForEach(item =>
{
var orderItem = ConvertOrderItem(item, products.Where(p => p.Pid == item.Pid).FirstOrDefault());
if (orderItem != null)
result.Add(orderItem);
});
return result;
}
}
}
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 进入详细评论页>>




