What's the difference between Entity Framework (6) transactions with single and multiple SaveChanges() calls

tab87vn

I want to know what are the practical differences of executing a transaction in the same database context between these 3 ways:

1) Multiple operations with one single SaveChanges(), without explicitly using a sql transaction

using (TestDbContext db = new TestDbContext())
{
    // first operation
    // second operation
    db.SaveChanges();
}

2) Multiple operations with one single SaveChanges(), using a sql transaction

using (TestDbContext db = new TestDbContext())
using (DbContextTransaction trans = db.Database.BeginTransaction())
{
     // operation 1
     // operation 2
     db.SaveChanges();    
     trans.commit();
}

3) Multiple operations with multiple SaveChanges(), using a sql transaction

using (TestDbContext db = new TestDbContext())
using (DbContextTransaction trans = db.BeginTransaction())
{
     // operation 1
     db.SaveChanges();    
     // operation 2
     db.SaveChanges();

     trans.commit();
}

In (2) and (3), if commit() is supposed to actually execute requested sql queries to database, is it really different, say, save changes for each operation or save changes for all operation at once?

And if (1) can also allow multiple operations to be safely executed in the same database context so what's the main use of manually starting a transaction? I'd say we can manually provide try/catch block to roll back the transaction if something bad happens, but AFAIK, SaveChanges() also covers it, automatically, at least with SQLServer.

** UPDATED: Another thing is: Should I make db context and transaction variables class-level or these should be local to containing methods only?

MutantNinjaCodeMonkey

If you do not start a transaction, it is implicit. Meaning, all SaveChanges() you perform will be available in the database immediately after the call.

If you start a transaction, SaveChanges() still performs the updates, but the data is not available to other connections until a commit is called.

You can test this yourself by setting break points, creating new objects, adding them to the context, and performing a SaveChanges(). You will see the ID property will have a value after that call, but there will be no corresponding row in the database until you perform a commit on the transaction.

As far as your second question goes, it really depends on concurrency needs, what your class is doing and how much data you're working with. It's not so much a scoping issue as it is a code execution issue.

Contexts are not thread safe, so as long as you only have one thread in your application access the context, you can make it at a broader scope. But then, if other instances of the application are accessing the data, you're going to have to make sure you refresh the data to the latest model. You also should consider that the more of the model you have loaded into memory, the slower saves are going to be over time.

I tend to create my contexts as close to the operations that are to be performed as possible, and dispose them soon after.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

what is the difference between Linq and entity framework

what's the difference between function calls?

Entity Framework 6 EntityDataSource not calling SaveChanges in DbContext

Entity Framework Transaction across multiple SaveChanges

What's the UML difference between Entity and Aggregate?

What's the difference between public and private transactions on the Quorum Blockchain

What's the difference between `*.framework`, `*.dylib` and `*.a` libs

What's the difference between Entity.Attributes and Entity.FormattedValues?

What is the difference between ForSqlServerHasIndex and HasIndex when configuring models in Entity Framework

what is difference between inverse property and foreign key in entity framework?

Why does a single Yubico show as multiple devices, what's the difference between hid-generic and input?

Can Entity Framework add many related entities with single SaveChanges()?

Entity Framework 7 SaveChanges

What should be the correct logical relation between these tables in Entity Framework 6

What is the difference between iText's getPageN() and getPageNRelease() calls?

System.OutOfMemoryException Entity Framework 6 for db.SaveChanges

Entity Framework 6 SaveChanges causes unique constraint exception

Calculating the difference between two column with NULL's using Entity Framework

Why is Entity Framework so slow to add multiple items in one SaveChanges()?

what is the difference between java ee 6 stack versus spring framework?

What is the difference between "Multiple" and "Single" for View Controller Presentation?

RealityKit – What's the difference between Anchor and Entity translation?

What's the difference between the following ways of instantiating an entity?

What's the difference between Perl 6's DEFINITE and defined methods?

Entity Framework 6 - Multiple DefaultConnectionFactory?

What's the difference between single and double equal signs (=) in shell comparisons?

what's the difference between using 'single quotes' or not in find command

What's the difference between `def` and `defp` in the Phoenix Framework?

What's the difference between the .NET Framework SDK and the Targeting pack

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive