我正在尝试使用Entity框架从Windows窗体DataGridView保存数据。由于某种原因,记录不会保存到数据库中。我想循环遍历DataGridView并将每一行添加到Transaction对象中,并立即将所有事务(行)保存到数据库中。
我在交易中发现的信息来自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 );
}
}
答案 0 :(得分:0)
您尚未插入oTransaction
或将其连接到某个现有对象。 EF不知道该对象存在。尝试AddObject
方法添加事务。这将它注册到EF。
此外,您可以删除Rollback
来电。它在没有提交时回滚。同时将消息框移出使用块以快速结束交易。