Database Reference
In-Depth Information
The best way to address this problem is to run DELETE statements against the database directly. Listing 16-21
shows you how to delete the Order and all corresponding OrderItems rows from the database.
Listing 16-21. Deleting Data: Executing DELETE statements against the database
int orderId = 50
context.Database.ExecuteSqlCommand(
@"delete from OrderItems where OrderId = @OrderId;
delete from Orders where OrderId = @OrderId",
new SqlParameter("OrderId", SqlDbType.Int) { Value = orderId });
Finally, if you already have an Order object loaded into the model, you can remove it after deletion with the code
shown in Listing 16-22.
Listing 16-22. Deleting Data: Removing an object from the model
context.Orders.Remove(order);
context.Entry(order).State = System.Data.Entity.EntityState.Detached;
Optimistic Concurrency
Preventing situations where multiple users update the same data, overriding each other's changes, is the one of the
most common business requirements you can find in systems. This is especially important with Entity Framework,
where UPDATE statements exclude columns that have not been modified in the object.
Consider the situation when two users work with the same order object simultaneously. Let's assume that one
user changes an article in OrderItem , which, in turn, changes its price and saves it to the database. At the same time,
another user changes the price in his or her in-memory OrderItem object without changing the article. When the
data is saved into the database, only the price column data would be updated, which makes the row data logically
inconsistent.
A common way to address these issues is by adding a timestamp column to the database table. SQL Server changes
its value every time a row is modified and, therefore, you can detect if the row has been changed after you loaded it.
Entity Framework supports this technique. You can mark the class property as a concurrency token in the
mapping class similar to how we did it with the non-unicode string attribute in Listing 16-16. Listing 16-23 shows you
how to set this property.
Listing 16-23. Setting the concurency token property
/* Setting up mapping in configuration */
internal class CustomerMap : EntityTypeConfiguration<Customer>
{
public CustomerMap()
{
Property(t => t.Email).IsUnicode(false);
Property(t => t.Ver)
.IsConcurrencyToken()
.HasDatabaseGeneratedOption(
DatabaseGeneratedOption.Computed
);
}
}
 
Search WWH ::




Custom Search