看了一遍“周大框”的项目,因为当时写的写的前端,所以后端有些地方还是不太懂。今天心血来潮,把原来模糊的知识点总结以下,以便以后开发作为参考。有总结错误的地方希望大家多批评指正。
架构
1、Model(实体层)
主要用于存放和数据库对应的模型和对模型本身操作的方法。
新建过程:
①先建立实体类库Model,打开项目,在解决方案中右键–》添加–》新建项目–》选中类库–》改名Model–》确定
②选中Model类库–》Shift+ALT+C–》建立实体类。
public class Order
{
[Key]
public long Id { get; set; }
public List<OrderItem> ItemList { get; set; }
public string CreateTime { get; set; }
public double TotalPrice { get; set; }
public Customer Customer { get; set; }
public Double CalculatePrice()
{
double price = 0;
return price;
}
}
2、DAL(数据访问层)
针对需求的需要,负责对实体进行增删改查,一般该层引用实体层
新建过程:
①先建立数据访问层类库DAL,打开项目,在解决方案中右键–》添加–》新建项目–》选中类库–》改名DAL–》确定
②在DAL中添加对Model的引用,选中DAL–》Alt+P+R–》解决方案–》项目–》选中MOdel–》确定
③建立数据访问类,选中DAL–》Shift+ALT+C–》建立数据访问类。
public class OrderRepository
{
protected ZDKContext _context;
public OrderRepository(ZDKContext context)
{
_context = context;
}
public void AddOrder(Order order)
{
var orders = _context.Orders;
orders.Add(order);
_context.SaveChanges();
}
public List<Order> GetOrders()
{
return _context.Orders.Include("ItemList.Frame.Shape").Include("ItemList.Frame.Wire").ToList();
}
}
3、BLL(业务逻辑层)
主要访问DAL,对DAL获取的对象进行业务处理比如校验等等,传递给UI的controller,一般对Model和DAL添加引用
①先建立业务逻辑层类库BLL,打开项目,在解决方案中右键–》添加–》新建项目–》选中类库–》改名BLL–》确定
②在BLL中添加对Model、DAL的引用,选中BLL–》Alt+P+R–》解决方案–》项目–》选中MOdel、DAL–》确定
③建立业务逻辑类,选中BLL–》Shift+ALT+C–》建立业务逻辑类。
public class OrderService
{
private WireRepository _wireRepository;
private ShapeRepository _shapeRepository;
private OrderRepository _orderRepository;
private CustomerRepository _customerRepository;
public OrderService(WireRepository wireRepository, ShapeRepository shapeRepository, OrderRepository orderRepository, CustomerRepository customerRepository)
{
_wireRepository = wireRepository;
_shapeRepository = shapeRepository;
_orderRepository = orderRepository;
_customerRepository = customerRepository;
}
public string validateAndSave(Order order)
{
//创建订单对象
order.CreateTime = DateTime.Now.ToString();
double orderPrice = 0;
foreach (OrderItem item in order.ItemList)
{
if(!ValidateFramePrice(item.Frame.Wire, item.Frame.Shape, item.Frame.SinglePrice))
{
return "订单项金额有误";
}
orderPrice += item.Frame.SinglePrice*item.Number;
}
if (Math.Abs(orderPrice - order.TotalPrice) < 0.01)
{
order.Customer = _customerRepository.GetCustomer();
_orderRepository.AddOrder(order);
return "OK";
}
return "订单金额计算有误";
}
}
4、UI(表现层)
一般添加对DAL、Model、BLL的引用
UI中的controller主要对BLL return的对象进行处理,比如说序列化、对序列化的结果写入http响应等等