删除项目,如果订单没有更多项目,则删除整个订单

时间:2016-08-01 10:16:32

标签: c# entity-framework

以下代码永远不会删除订单,即使最后一项被删除 - 为什么?如果没有更多物品,我想删除订单吗?

    int orderItemId = 5;
    OrderItem orderItem = DbContext.OrderItem.Find(orderItemId);
    Order order = DbContext.Order.Find(orderItem.OrderId);

    DbContext.OrderItem.Remove(orderItem);

    if (DbContext.OrderItem.Count(x => x.OrderId == order.Id) == 0)
    {
           DbContext.Order.Remove(order);
    }

    DbContext.SaveChanges();

2 个答案:

答案 0 :(得分:1)

DbContext.OrderItem.Remove(orderItem); // [1]

if (DbContext.OrderItem.Count(x => x.OrderId == order.Id) == 0) // [2]
{
    DbContext.Order.Remove(order);
}

DbContext.SaveChanges(); // [3]

当您从orderItem行的OrderItem集合中删除[1]时,它实际上并未在数据库中删除。系统只会在SaveChanges()[3]电话上删除。在此之前,orderItem仅发布以供删除但未删除。

但是当您查询[2]行上的项目数时 - 会从数据库中查询该数据库,该数据库包含orderItem

在检查现有项目之前,您需要将更改提交到数据库:

DbContext.OrderItem.Remove(orderItem);
DbContext.SaveChanges();

if (!DbContext.OrderItem.Any(x => x.OrderId == order.Id))
{
    DbContext.Order.Remove(order);
    DbContext.SaveChanges();
}

答案 1 :(得分:0)

您需要首先删除项目,然后刷新。试试这个更强大的解决方案并告诉我你得到了什么结果:

var id = "2";
var orderItem = db.OrderItems.SingleOrDefault(item => item.Id == id);

if(orderItem != null)
{
    // The items exists. So we remove it and calling 
    // the db.SaveChanges this will be removed from the database.
    db.OrderItems.Remove(orderItem);
    db.SaveChanges();

    // Refresh or update any visible data with the new data source.
    refreshGrid();
}
else {
    // Replace orderItem.Id with identifying order item property.
    Console.WriteLine(
        String.Format("Attempted to remove order {0}, but it could not be found.", orderItem.Id)
    );
}