实体框架回滚事务(如果发生错误)

时间:2019-02-25 17:41:01

标签: c# entity-framework

 public string ProcessStockData(
        int nQuantity,
        int itemId,
        int locId)

    {
        Entities entities = new Entities();

        int nQuantity = 3;
        int itemId = 1;
        int locId = 1312;

        int inventoryLocId;

        var tab1 = entities.table1.FirstOrDefault(x => x.id == itemId);
        tab1.Tstock -= nQuantity;
        tab1.locationId -= locId;

        var tab2 = entities.table2.FirstOrDefault(x => x.itemid == Id && x.locId == locId);
        if (tab2 != null)
        {
            tab2.stock -= nQuantity;
            inventoryLocId = tab2.id;
        }
        else
        {

            var tab2Obj = new table2
            {
                itemid = itemId,
                locId = locId,
                stock = -nQuantity,
            };
            entities.table2.Add(tab2Obj);
            entities.SaveChanges();
            inventoryLocId = entities.table2.Max(u => u.id);
        }

        var log = new LogStockInfo
        {
            itemid = itemid,
            locId = locId,
            stock = -nQuantity,
            inventoryLocId = inventoryLocId
        };
        entities.LogStockInfo.Add(log);
        entities.SaveChanges();
    }

我有3个表,针对数据进行更新。 我具有ProcessStockData函数,其中针对这3个表进行了操作。 Fisrt table1数据已更新。此外,还必须有针对table1的数据。这就是为什么我不应用空检查的原因。

在更新table2之后。 如果记录在表2中可用,则将对其进行更新。我获取主键值。 添加了其他新记录,之后,我使用Max查询获取主键值。

如果将新记录添加到table2,则在将记录添加到LogStockInfo时发生错误。 之后,我在LogStockInfo中记录库存变化。

在这种情况下,我想回滚以前的表(table1和table2)的更改。 在实体框架中有什么方法可以做。

0 个答案:

没有答案