Entity Framework 4.1 (strong conversion)

Source: Internet
Author: User

Original article name: Entity Framework 4.1: Optimistic Concurrency (6)

Address: http://vincentlauzon.wordpress.com/2011/04/17/entity-framework-4-1-optimistic-concurrency-6/

We can see the English tutorial recommended for Entity Framework 4.1. To help you look more convenient, we can translate it briefly. This is a series of 8 articles, and this is 8th articles.
  1. One of Entity Framework 4.1: Basic
  2. Entity Framework 4.1 II: overwrite the default conventions
  3. Entity Framework 4.1 3: greedy loading and delayed Loading
  4. Entity Framework 4.1 4: complex types
  5. Entity Framework 4.1-5: Multi-to-many relationships
  6. Entity Framework 4.1: Optimistic Concurrency
  7. Entity Framework 4.1 7: Inheritance
  8. Entity Framework 4.1: bypassing EF query ing

This article discusses optimistic concurrency.

We often face the issue of concurrent access to multiple users. This is because the speed at which a person accesses a machine cannot match that of a high-speed machine. In typical cases, it takes about one minute or more to fill in data, and the transaction processing of a machine usually takes less than one second.

When the user edits the corresponding data, we cannot keep the transaction processing of the database open for many reasons: connection problems, trust problems, technical reasons, and so on. For these reasons, we need concurrency management. There are two management methods: optimistic and pessimistic. The pessimistic approach is more difficult to deal with, because you need to implement a record-based locking mechanism, and there are also some problems, such as how long the system should lock before the lock is automatically released. Optimistic Concurrency should be simpler.

A basic assumption of Optimistic Concurrency is that user modifications rarely conflict with each other. For applications with few users editing the same data at the same time, no matter how many users or few users are there, it is true. The basic consideration is to provide a data version for the user accessing the data. When the user returns to update the data later, the original data is confirmed through the version, if the data has been updated by other operations in the background and the version has changed, we can detect the version and reject the update.

There are many ways to implement the version, including associating a version number to the data. It can be the Last modified Date and time field or more than one field. In EF, this is calledConcurrenty tokenIn this article, I use the time-stamp feature of SQL Server, which requires a time-stamp column to be added to the table. We can use it to achieve optimistic concurrency. The SQL Server maintains this column each time the record is updated.

To tell EF that there is an attribute in the entity that represents a concurrent identifier, you can identify this attribute through the tag [concurrencycheck], or use the model builder. I think the concurrent identity defines business rules and should be part of the model. So the label is used here.

Public class order
{
Public int orderid {Get; set ;}
[Required]
[Stringlength (32, minimumlength = 2)]
Public String ordertitle {Get; set ;}
[Required]
[Stringlength (64, minimumlength = 5)]
Public String customername {Get; set ;}
Public datetime transactiondate {Get; set ;}
[Concurrencycheck]
1544020384
Public byte [] timestamp {Get; set ;}

Public Virtual list <orderdetail> orderdetails {Get; set ;}
Public Virtual list <employee> involvedemployees {Get; set ;}
}

In this Code, when we call savechanges through dbcontext, optimistic concurrency will be used.

The type of the timestamp attribute is byte []. The timestamp label maps this attribute to the time-stamp type column of SQL Server.

Now we simulate concurrency, And we will perform the following three steps:

  1. Create an order
  2. Simulate user X to modify this order
  3. Simulate user y to modify this order. At this time, the Order has been modified, but user y does not know.

The modification process is simulated by connecting objects in another dbcontext. When we connect objects through dbcontet, it assumes that the objects are not modified, so we modify them later.

Private Static void concurrencycheck ()
{
Order originalorder;

// Create an order
Using (VAR context1 = new mydomaincontext ())
{
Originalorder = New Order
{
Ordertitle = "paper ",
Customername = "* bob *",
Transactiondate = datetime. Now
};

Context1.orders. Add (originalorder );
Context1.savechanges ();
}
// Simulate the modification of the created order by user X
Using (VAR context2 = new mydomaincontext ())
{// Recreate the order object in order to attach it
VaR order = New Order
{
Orderid = originalorder. orderid,
Ordertitle = originalorder. ordertitle,
Customername = originalorder. customername,
Transactiondate = originalorder. transactiondate,
Timestamp = originalorder. Timestamp
};

Context2.orders. Attach (order );

// Alter the order
Order. customername = "Robert ";

Context2.savechanges ();
}
// Simulate the modification of the created order by user y (after user X already modified it)
Using (VAR context3 = new mydomaincontext ())
{// Recreate the order in order to attach it
VaR order = New Order
{
Orderid = originalorder. orderid,
Ordertitle = originalorder. ordertitle,
Customername = originalorder. customername,
Transactiondate = originalorder. transactiondate,
Timestamp = originalorder. Timestamp
};

Context3.orders. Attach (order );

// Alter the order
Order. customername = "Luke **";

Try
{
Context3.savechanges ();
}
Catch (dbupdateconcurrencyexception ex)
{
Console. writeline ("concurrency exception on" + ex. Entries. First (). Entity. GetType (). Name );
}
}
}

You can also force EF to believe that the order has been modified.

Context3.entry (order). State = entitystate. modified;

Therefore, EF provides out-of-the-box support for Optimistic Concurrency. This tip can also be used in all aspects of the EF state: When you connect entities, make sure they are in the correct state.

  • Detached
  • Unchanged
  • Added
  • Deleted
  • Modified

Original article name: Entity Framework 4.1: Optimistic Concurrency (6)

Address: http://vincentlauzon.wordpress.com/2011/04/17/entity-framework-4-1-optimistic-concurrency-6/

We can see the English tutorial recommended for Entity Framework 4.1. To help you look more convenient, we can translate it briefly. This is a series of 8 articles, and this is 8th articles.
  1. One of Entity Framework 4.1: Basic
  2. Entity Framework 4.1 II: overwrite the default conventions
  3. Entity Framework 4.1 3: greedy loading and delayed Loading
  4. Entity Framework 4.1 4: complex types
  5. Entity Framework 4.1-5: Multi-to-many relationships
  6. Entity Framework 4.1: Optimistic Concurrency
  7. Entity Framework 4.1 7: Inheritance
  8. Entity Framework 4.1: bypassing EF query ing

This article discusses optimistic concurrency.

We often face the issue of concurrent access to multiple users. This is because the speed at which a person accesses a machine cannot match that of a high-speed machine. In typical cases, it takes about one minute or more to fill in data, and the transaction processing of a machine usually takes less than one second.

When the user edits the corresponding data, we cannot keep the transaction processing of the database open for many reasons: connection problems, trust problems, technical reasons, and so on. For these reasons, we need concurrency management. There are two management methods: optimistic and pessimistic. The pessimistic approach is more difficult to deal with, because you need to implement a record-based locking mechanism, and there are also some problems, such as how long the system should lock before the lock is automatically released. Optimistic Concurrency should be simpler.

A basic assumption of Optimistic Concurrency is that user modifications rarely conflict with each other. For applications with few users editing the same data at the same time, no matter how many users or few users are there, it is true. The basic consideration is to provide a data version for the user accessing the data. When the user returns to update the data later, the original data is confirmed through the version, if the data has been updated by other operations in the background and the version has changed, we can detect the version and reject the update.

There are many ways to implement the version, including associating a version number to the data. It can be the Last modified Date and time field or more than one field. In EF, this is calledConcurrenty tokenIn this article, I use the time-stamp feature of SQL Server, which requires a time-stamp column to be added to the table. We can use it to achieve optimistic concurrency. The SQL Server maintains this column each time the record is updated.

To tell EF that there is an attribute in the entity that represents a concurrent identifier, you can identify this attribute through the tag [concurrencycheck], or use the model builder. I think the concurrent identity defines business rules and should be part of the model. So the label is used here.

Public class order
{
Public int orderid {Get; set ;}
[Required]
[Stringlength (32, minimumlength = 2)]
Public String ordertitle {Get; set ;}
[Required]
[Stringlength (64, minimumlength = 5)]
Public String customername {Get; set ;}
Public datetime transactiondate {Get; set ;}
[Concurrencycheck]
1544020384
Public byte [] timestamp {Get; set ;}

Public Virtual list <orderdetail> orderdetails {Get; set ;}
Public Virtual list <employee> involvedemployees {Get; set ;}
}

In this Code, when we call savechanges through dbcontext, optimistic concurrency will be used.

The type of the timestamp attribute is byte []. The timestamp label maps this attribute to the time-stamp type column of SQL Server.

Now we simulate concurrency, And we will perform the following three steps:

  1. Create an order
  2. Simulate user X to modify this order
  3. Simulate user y to modify this order. At this time, the Order has been modified, but user y does not know.

The modification process is simulated by connecting objects in another dbcontext. When we connect objects through dbcontet, it assumes that the objects are not modified, so we modify them later.

Private Static void concurrencycheck ()
{
Order originalorder;

// Create an order
Using (VAR context1 = new mydomaincontext ())
{
Originalorder = New Order
{
Ordertitle = "paper ",
Customername = "* bob *",
Transactiondate = datetime. Now
};

Context1.orders. Add (originalorder );
Context1.savechanges ();
}
// Simulate the modification of the created order by user X
Using (VAR context2 = new mydomaincontext ())
{// Recreate the order object in order to attach it
VaR order = New Order
{
Orderid = originalorder. orderid,
Ordertitle = originalorder. ordertitle,
Customername = originalorder. customername,
Transactiondate = originalorder. transactiondate,
Timestamp = originalorder. Timestamp
};

Context2.orders. Attach (order );

// Alter the order
Order. customername = "Robert ";

Context2.savechanges ();
}
// Simulate the modification of the created order by user y (after user X already modified it)
Using (VAR context3 = new mydomaincontext ())
{// Recreate the order in order to attach it
VaR order = New Order
{
Orderid = originalorder. orderid,
Ordertitle = originalorder. ordertitle,
Customername = originalorder. customername,
Transactiondate = originalorder. transactiondate,
Timestamp = originalorder. Timestamp
};

Context3.orders. Attach (order );

// Alter the order
Order. customername = "Luke **";

Try
{
Context3.savechanges ();
}
Catch (dbupdateconcurrencyexception ex)
{
Console. writeline ("concurrency exception on" + ex. Entries. First (). Entity. GetType (). Name );
}
}
}

You can also force EF to believe that the order has been modified.

Context3.entry (order). State = entitystate. modified;

Therefore, EF provides out-of-the-box support for Optimistic Concurrency. This tip can also be used in all aspects of the EF state: When you connect entities, make sure they are in the correct state.

  • Detached
  • Unchanged
  • Added
  • Deleted
  • Modified

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.