c# - Foreach 循环中的 Entity Framework 事务

标签 c# .net transactions entity-framework-6

我正在尝试使用 Entity Framework 从 Windows 窗体 DataGridView 保存数据。由于某种原因,记录不会保存到数据库中。我想遍历 DataGridView 并将每一行添加到一个事务对象中,并立即将所有事务(行)保存到数据库中。

我找到的交易信息来自 MSDN 。在寻找问题的解决方案时,我遇到了 this SO post,它有一条评论,上面写着“我正在采取异常来捕获这样的异常。它会导致数据库操作静默失败。”这似乎是我的代码中发生的事情。我没有收到任何错误,它只是没有将任何内容保存到数据库中。

如何自动保存所有事务并在出现故障时回滚?我如何重新组织事物以正确捕获错误?如果评论是正确的,那么 MSDN 的代码有什么问题?

这是我的代码:

// Store the valid transactions
using ( var dbContextTransaction = context.Database.BeginTransaction() )
{
    try
    {
        Transaction oTransaction = new Transaction();

        foreach ( DataGridViewRow row in dgvInventoryTransactions.Rows )
        {
            if ( !row.IsNewRow )
            {
                // Get the product
                int iSelectedProduct = int.Parse( row.Cells[0].Value.ToString() );
                oTransaction.Product = context.Products.First( p => p.ID == iSelectedProduct );

                // Quantities
                oTransaction.FullQuantity = int.Parse( row.Cells[1].Value.ToString() );
                oTransaction.PartialQuantity = int.Parse( row.Cells[2].Value.ToString() );
                oTransaction.CalculatedQuantity = (double)oTransaction.FullQuantity + ( (double)oTransaction.PartialQuantity / (double)oTransaction.Product.Pieces );

                // Check to see if a truck has been selected
                if ( !string.IsNullOrEmpty( row.Cells[3].FormattedValue as String ) )
                {
                    // A truck has been selected
                    int iSelectedVehicle;
                    if ( int.TryParse( row.Cells[3].FormattedValue.ToString(), out iSelectedVehicle ) )
                    {
                        oTransaction.Vehicle = context.Vehicles.Where( v => v.VehicleNumber == iSelectedVehicle ).First();
                    }

                }

                // Check to see if the "Source" field contains data
                if ( !string.IsNullOrEmpty( row.Cells[4].FormattedValue as String ) )
                {
                    oTransaction.SourceNumber = row.Cells[4].Value.ToString();
                }

                // Check to see if the comments field contains data
                if ( !string.IsNullOrEmpty( row.Cells[5].FormattedValue as String ) )
                {
                    oTransaction.Comments = row.Cells[5].Value.ToString();
                }

                // Get the transaction type
                int value = int.Parse( cmboTransactionType.SelectedValue.ToString() );
                oTransaction.TransactionType = context.TransactionTypes.Where( t => t.ID == value ).First();

                // Get the current user
                var user = context.Employees.First( u => u.ID == Globals.User ); // One lookup...
                oTransaction.CreatedBy = user;
                oTransaction.LastUpdatedBy = user;                                     

                // Add the dates
                oTransaction.TransactionDate = dtpTransactionDate.Value;
                oTransaction.CreateDate = DateTime.Now;
                oTransaction.LastUpdatedDate = DateTime.Now;

                // Save the transaction
                context.SaveChanges();


            }

        }

        // Commit the changes to the database
        dbContextTransaction.Commit();

    }
    catch ( Exception )
    {
        dbContextTransaction.Rollback();
        MessageBox.Show( "Records were NOT saved successfully.", "Save Unsuccessful", MessageBoxButtons.OK, MessageBoxIcon.Information );
    }

}

最佳答案

您尚未插入 oTransaction 或将其连接到某个现有对象。 EF 不知道这个对象存在。尝试使用 AddObject 方法添加事务。这会将其注册到 EF。

此外,您还可以删除 Rollback 调用。它在没有提交时回滚。还将消息框移出 using block 以快速结束事务。

关于c# - Foreach 循环中的 Entity Framework 事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34927463/

相关文章:

c# - 如何在 WPF 应用程序中配置 StructureMap?

c# - 如何使用我自己的由列表支持的 IQueryable 进行延迟加载

.net - 如何安装 XamlPad?

c# - ref struct 中不能使用 Yield 关键字?

postgresql - select txid_current 和 select txid_current_snapshot 的区别

java - 使用@Transactional 注解的问题

c# - Windows Phone 8 上的应用程序之间的 UniqueDeviceID 不同

c# - 在 C++ dll 中分配内存,在 C# 中释放

c# - 在自定义类中处理异常

java - 使用 DAO 设计模式在 Hibernate 中进行事务管理