gpt4 book ai didi

c# - 使用 EF 的 DbContext.ExecuteSqlCommand() 进行交易时出现异常

转载 作者:行者123 更新时间:2023-11-30 19:40:08 25 4
gpt4 key购买 nike

使用 try-catch 结构,我试图弄清楚如果在事务的任何一点捕获到异常该怎么办。下面是一个代码示例:

try
{
DbContext.ExecuteSqlCommand("BEGIN TRANSACTION"); //Line 1
DBContext.ExecuteSqlCommand("Some Insertion/Deletion Goes Here"); //Line 2
DbContext.ExecuteSqlCommand("COMMIT"); //Line 3
}
catch(Exception)
{
}

如果预期在执行“第 1 行”时被捕获,除了警告错误之外什么都不要做。如果它在执行第二行时被发现,我不知道我是否需要尝试回滚已成功打开的事务,如果第三行出现问题,也会发生同样的情况。

我应该只发送回滚吗?或者在一个方法调用中将所有命令直接发送到银行?

在 try-catch 中有一个循环执行许多事务,就像示例中的事务一样(我需要很多小事务而不是一个大事务,这样我就可以正确地重用 SQL 的“_log”文件并避免它增长不必要的)。

如果任何事务出错,我只需要将它们全部删除并告知未发生的情况,但我不能将其变成一个大事务,只能使用回滚,否则会使日志文件变大到 40GB。

最佳答案

认为这会有所帮助:

using (var ctx = new MyDbContext())
{
// begin a transaction in EF – note: this returns a DbContextTransaction object
// and will open the underlying database connection if necessary
using (var dbCtxTxn = ctx.Database.BeginTransaction())
{
try
{
// use DbContext as normal - query, update, call SaveChanges() etc. E.g.:
ctx.Database.ExecuteSqlCommand(
@"UPDATE MyEntity SET Processed = ‘Done’ "
+ "WHERE LastUpdated < ‘2013-03-05T16:43:00’");

var myNewEntity = new MyEntity() { Text = @"My New Entity" };
ctx.MyEntities.Add(myNewEntity);
ctx.SaveChanges();

dbCtxTxn.Commit();
}
catch (Exception e)
{
dbCtxTxn.Rollback();
}
} // if DbContextTransaction opened the connection then it will close it here
}

取自:https://entityframework.codeplex.com/wikipage?title=Improved%20Transaction%20Support

基本上,它的想法是您的事务成为 using block 的一部分,并且在其中您可以使用实际的 sql 进行 try/catch。如果在 try/catch 中有任何失败,它将被回滚

关于c# - 使用 EF 的 DbContext.ExecuteSqlCommand() 进行交易时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24704953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com