Master Detail,MVC Model层代码,以更好的专业方式

时间:2011-12-29 09:47:44

标签: c# asp.net asp.net-mvc-3 entity-framework-4 crud

我正在尝试在Asp.net MVC模型中编写主细节条目编辑 首先,让我向您展示我的两个模型类。

类名= Model \ OrderDetailRepository.cs

public class OrderDetailRepository : IOrderDetailRepository
{
    NorthwindEntities DB = new NorthwindEntities();

    public IQueryable<Order_Detail> GetOrderDetailByOrderID(int OrderID)
    {
        return DB.Order_Details.Where(tableX => tableX.OrderID == OrderID);
    }

    public void InsertOrderDetail(Order_Detail _Order_Detail)
    {
        DB.Order_Details.AddObject(_Order_Detail);
    }


    public void UpdateOrderDetail(Order_Detail _Order_Detail)
    {
        DB.ObjectStateManager.ChangeObjectState(_Order_Detail, EntityState.Modified);
    }

    public void DeleteOrderDetailByOrderID(int OrderID)
    {
        Order_Detail  _Order_Detail = DB.Order_Details.SingleOrDefault(x => x.OrderID == OrderID);

        if (_Order_Detail != null)
            DB.Order_Details.DeleteObject(_Order_Detail);
    }

    public void DeleteOrderDetailByCurrentRecord(Order_Detail _Order_Detail)
    {
        DB.Order_Details.DeleteObject(_Order_Detail);
    }

    public void Commit()
    {
        DB.SaveChanges();
    }
}

班级名称=型号\ OrderMasterReposity.cs

public class OrderMasterReposity : IOrderMasterRepository
{
    NorthwindEntities DB = new NorthwindEntities();

    public IQueryable<Order> GetOrderMasterByOrderID(int OrderID)
    {
        return DB.Orders.Where(tableX => tableX.OrderID == OrderID);   
    }

    public void InsertOrderMaster(Order _Order)
    {
        DB.Orders.AddObject(_Order);
    }

    public void UpdateOrderMaster(Order _Order)
    { 
        DB.ObjectStateManager.ChangeObjectState(_Order,  EntityState.Modified);
    }

    public void DeleteOrderMaster(int OrderID)
    { 
        Order _Order = DB.Orders.SingleOrDefault(x => x.OrderID == OrderID);

        if (_Order != null)
            DB.Orders.DeleteObject(_Order);            
    }

    public void Commit()
    {
        DB.SaveChanges();
    }
}

在所有高级代码之后,我需要从我的控制器类中调用这两个类。 所以我们假设下面的代码我将在控制器层写入。

OrderMasterReposity _OrderMasterReposity = new OrderMasterReposity();
OrderDetailRepository _OrderDetailRepository = new OrderDetailRepository();
_OrderMasterReposity.InsertOrderMaster(new Order{....});
_OrderDetailRepository.InsertOrderDetail(new Order_Detail{....});
_OrderMasterReposity.Commit();
_OrderDetailRepository.Commit();

我的问题是我现在的做法不是那么专业。
因为我需要多次调用Commit函数 那么,请有人能给我更好的方法在Model层编码吗?

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

最好的是你正确实施Repository模式 此外,没有订单,Order详细信息没有意义,因此根据DDD,您不应为order_detail定义单独的存储库。我会这样做

Order _order = OrderMasterRepository.GetOrder(orderID);
_order.Property1 = value1;
_order.Property2 = value2;
_order.Property3 = value3;
foreach(var orderDetail in _order.OrderDetails)
{
   orderDetail.Property1 = avalue1;
   orderDetail.Property2 = avalue2;
   .
   .
} 
OrderMasterRepository.Commit();

以上语句将在order和orderDetail表中保存数据。