使用 EF6,您可以使用以下事务:
using (var context = new PostEntityContainer())
{
using (var dbcxtransaction = context.Database.BeginTransaction())
{
try
{
PostInformation NewPost = new PostInformation()
{
PostId = 101,
Content = "This is my first Post related to Entity Model",
Title = "Transaction in EF 6 beta"
};
context.Post_Details.Add(NewPost);
context.SaveChanges();
PostAdditionalInformation PostInformation = new PostAdditionalInformation()
{
PostId = (101),
PostName = "Working With Transaction in Entity Model 6 Beta Version"
};
context.PostAddtional_Details.Add(PostInformation);
context.SaveChanges();
dbcxtransaction.Commit();
}
catch
{
dbcxtransaction.Rollback();
}
}
}
当事情出现问题时,是否真的需要回滚?我很好奇,因为“提交”说明中写道:“提交基础存储事务。”
这让我很好奇,因为在我看来,如果没有调用提交函数,则之前执行的命令将不会被存储(这对我来说似乎是合理的)。但如果是这种情况,调用回滚函数的原因将是什么?在EF5中,我使用了TransactionScope,它没有回滚函数(只有完成函数),这对我来说似乎是合理的。由于MS DTC的原因,我不能再使用TransactionScope,但我也不能像上面的示例一样使用try catch(即,我只需要提交)。
SaveChanges
)。 - Pawel