Entity Framework 6 Recipes 2nd Edition (9-6)-& gt; manage the concurrency when disconnected, entityrecipes

Source: Internet
Author: User

Entity Framework 6 Recipes 2nd Edition (9-6)-> Manage the concurrency when disconnected, entityrecipes

9-6. Manage the concurrency During disconnection

Problem

You want to ensure that only the entities whose concurrent tokens are not modified on the WCF client are accepted.

Solution

We have a model shown in Figure 9-6.

 

Figure 9-6 Order entity model

We want to use the WCF Service to update an order, but make sure that this order has not been modified since we retrieved it last time.

Later we will demonstrate two different methods. Both use a TimeStamp column for concurrency control.

1. Create a New WCF Service library, right-click solution, select "New Project", select the WCF external WCF Service library, and name it Recipe6.

2. right-click the project, select "add" external "new item", and select "data export ADO. NET object data model. select the Order table in the Wizard. in the EF model design diagram, right-click the TimeStamp attribute, select "attribute", and set "concurrency mode" to Fixed.

3. Use the code in Listing 9-30 to define the services in the IService1.cs file.

Listing 9-30.Our WCF Service Contract

[ServiceContract]

Public interface IService1

{

[OperationContract]

Order InsertOrder ();

[OperationContract]

Void UpdateOrderWithoutRetrieving (Order order );

[OperationContract]

Void UpdateOrderByRetrieving (Order order );

}

4. Use the Listing 9-31 code to implement services in the Service1.cs file.

Listing 9-31.The Implementation of Our Service Contract

Public class Service1: IService1

{

Public Order InsertOrder ()

{

Using (var context = new EFRecipesEntities ())

{

// Delete the previous test data

Context. Database. ExecuteSqlCommand ("delete from chapter9. [order]");

Var order = new Order {Product = "Camping Tent", Quantity = 3, Status = "Received "};

Context. Orders. Add (order );

Context. SaveChanges ();

Return order;

}

}

 

Public void UpdateOrderWithoutRetrieving (Order order)

{

Using (var context = new EFRecipesEntities ())

{

Try

{

Context. Orders. Attach (order );

If (order. Status = "Received ")

{

Context. Entry (order). Property (x => x. Quantity). IsModified = true;

Context. SaveChanges ();

}

}

Catch (OptimisticConcurrencyException ex)

{

// Handle concurrency exceptions

}

}

}

 

Public void UpdateOrderByRetrieving (Order order)

{

Using (var context = new EFRecipesEntities ())

{

// Obtain the current object from the database

Var dbOrder = context. Orders. Single (o => o. OrderId = order. OrderId );

// Execute concurrent check

If (dbOrder! = Null & StructuralComparisons. StructuralEqualityComparer. Equals (order. TimeStamp, dbOrder. TimeStamp ))

{

DbOrder. Quantity = order. Quantity;

Context. SaveChanges ();

}

Else

{

// Handle concurrency issues

}

}

}

}

5. for the test service, we create a console application in the solution. right-click the Service Project, select "debug", start the new instance, and add a reference to the Service in the control project. The console project code is shown in Listing 9-32.

Listing 9-32.The Client We Use to Test Our WCF Service

Class Program

{

Static void Main (string [] args)

{

Var service = new ServiceReference1.Service1Client ();

Var order = service. InsertOrder ();

Order. Quantity = 5;

Service. UpdateOrderWithoutRetrieving (order );

Order = service. InsertOrder ();

Order. Quantity = 3;

Service. UpdateOrderByRetrieving (order );

}

}

If you set a breakpoint before the Main () method and execute the statement by statement, the code runs on the server.

How does it work?

The InsertOrder () method (see Listing 9-31) deletes the previous test data, inserts a new order, and returns an order containing the correct ID and TimeStamp. on our client, we use two slightly different methods to update this order.

The first method is to use UpdateOrderWithoutRetrieving (): First Attach the order () passed from the client to DbContext, and then determine whether the order status is "already ed ", if the object's Quantity attribute state is set to modified, then call

SaveChanges (). EF generates an update SQL statement. Its Where clause contains OrderId and TimeStamp. if the data in the database before SaveChanges () has been modified, an exception will occur (the storage area update, insert, or delete statement affects the number of unexpected rows (0 ). Objects may be modified or deleted after being loaded. Refresh the ObjectStateManager item .). We use try and catch to catch exceptions. this ensures that the data in the database has not been modified after the Order submitted by the client runs InsertOrder. in fact, we can perform concurrent checks before saving, and compare the TimeStamp attribute value of the order returned from the client with the database value. This is the method used in the UpdateOrderByRetrieving () method.

Appendix: script file of the database used in the Creation example

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.