Home Entity Framework: Is the completely transaction complete after SaveData?
Reply: 1

Entity Framework: Is the completely transaction complete after SaveData?

WebDevGuy2
1#
WebDevGuy2 Published in 2018-02-13 18:46:45Z

Working on MVC5, EntityFramework6 web application. Usually in my classes I define my context var in the class scope...

[Authorize]
public class MyResultsController : Controller
{
    private readonly XYZ_MyContext db = new XYZ_MyContext();

Then I just reference 'db' whenever I want to access the context.

In my methods that save data I do it like this...

this.db.SaveChanges();

I typically dont use a Using statement.

My questions are....

(1) At the point you call SaveChanges, if it doesn't error out, then the transaction is complete right? You dont have to explicitly end it? (The data isn't cached temporarily, etc...)

(2) Also, if I see the actual data in the database is the transaction 100% complete for sure? In other words, if I can see the data in the data table (via SSMS), the data won't just "disappear" unless it's explicitly deleted, right?

Thanks!

Nick Orlando
2#
Nick Orlando Reply to 2018-02-14 14:06:00Z

Yes. If the line where you've called SaveChanges() completes without throwing an exception, the transaction will be complete.

In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes. When you execute another such operation a new transaction is started.

See MSDN documentation

Also, if I see the actual data in the database is the transaction 100% complete for sure?

If you're doing an INSERT wrapped in a transaction, and you subsequently do a SELECT from the same table to which you are inserting, then you would not see any results of your insert until the transaction completes, unless you include a WITH (NOLOCK) hint on your SELECT query.

If you do a SELECT and you do include a WITH (NOLOCK) hint, then it is possible to get a "dirty read", where you may see rows in your table that were inserted into the table during the transaction but may subsequently have been rolled back if the transaction failed.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.306951 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO