开发者

EF 4.1 Code First - wrap multiple calls to SaveChanges in a transaction

开发者 https://www.devze.com 2023-03-05 22:49 出处:网络
For reasons described here I need to make multiple calls to SaveChanges.I would like both of these calls to be wrapped up in a transaction (so that if the second call fails, 开发者_如何学运维the first

For reasons described here I need to make multiple calls to SaveChanges. I would like both of these calls to be wrapped up in a transaction (so that if the second call fails, 开发者_如何学运维the first call will roll back). For example:

AccountsContext context = new AccountsContext(connectionString);

CountryNotes notes = new CountryNotes();
notes.Notes = "First save";
context.SaveChanges();

notes.Notes = "Second save";
context.SaveChanges();

How do I put the above two calls to SaveChanges in a single transaction?

Thanks,

Paul.


Use TransactionScope:

using (var scope = new TransactionScope(TransactionScopeOption.Required, 
    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
    AccountsContext context = new AccountsContext(connectionString);

    CountryNotes notes = new CountryNotes();
    notes.Notes = "First save";
    context.SaveChanges();

    notes.Notes = "Second save";
    context.SaveChanges();

    scope.Complete();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消