How entity framework handles someone changing data underneath me (transactions)

Say have the following code:

public void SaveOrUpdate(OrderContract orderContract)
{
   foreach (var orderContract in orderContract.Tests)
   {

      Order order=dataAccess.FindOne<Order>(x=>x.OrderId==orderContract.OrderId) 
                  ?? new Order();

      // Where there are updates, put the stuff in the 
      // contract over what we already had.
      Mapper.Map(orderContract, order);

       // if it is new then add it in so it is inserted by EF.
      if (orderedTest.OrderedTestId <= 0)
          dataAccess.Add(orderedTest);

   }
   dataAccess.SaveChanges();
}

Does EF have anything that will care if someone updates an order after I retrieve it (in the FindOne call?

Or will it just happily overwrite any changes that have been done in between retrieving the data and my call to SaveChanges?

If it does not do that, then would a call ObjectContext.Connection.BeginTransaction be best to protect me? Or should I use new TransactionScope()?

And how can either of those know what rows I need to have in a transaction. (Just because I read a row does not mean that I want it locked. Or does it lock all tables in the model (yuck)).

Note: I am running with SQL Server 2008 R2 and EF 4.1

Answers


By default, yes it will overwrite changed records. If you are worried about it for your app, read this:

http://msdn.microsoft.com/en-us/library/bb738618.aspx

By default, the Entity Framework implements an optimistic concurrency model. This means that locks are not held on data in the data source between when the data is queried and the data is updated. The Entity Framework saves object changes to the database without checking for concurrency. For entities that might experience a high degree of concurrency, we recommend that the entity define a property in the conceptual layer with an attribute of ConcurrencyMode="fixed".....(follow link to read more)


Need Your Help

Is there a .Net API for Windows Error Reporting

.net windows windows-error-reporting

Is there a .Net API for me to integrate Windows Error Reporting into my application?

Sizing DataGrid to fit to its content when space available in WPF

.net wpf datagrid size height

I am new to WPF. I have got a DataGrid which is placed inside a Grid with row height set to "*" . I want this DataGrid height to fit to its content if the window height is not less than the total c...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.