Entity Framework 4 in action Reading Notes-Chapter 7: persistence object to database: persistence Techniques

Source: Internet
Author: User
7.4 persistence skills

Many things in the persistence process may cause errors, for example, the string is too long, the foreign key constraint is violated, the column that is not empty is set to null, repeat key, and so on. These are typical causes of exceptions. Let's see howCodeTo handle these exceptions.

7.4.1 handling persistence exceptions

Generally, exception handling is simple. You can call savechange in the try/Catch Block. The same is true for exceptions caused by EF, but a specific exception must be caught: updateexception. Updateexception contains information about the entry. In fact, Object Persistence causes an error.

The entry is public by the stateentries attribute. It is of the readonlycollection <objectstateentry> type. The stateentries attribute is a list because it returns an entityentry for the entity that causes the exception, plus all relationshipentry instances associated with it. You only receive one object, because the persistence process will stop as long as there is a problem, and the current entry is passed to this exception.

Important information is also stored in innerexception. You can findProgramThe original sqlexcption.

If you combine the internal exception information and the information in entries, you can build a log record, which is useful for understanding where errors occur. If you want to go further, you can build a form to give the user enough information to understand what the problem is and how to solve it. The following list shows how to obtain exceptions and write logs.

Listing 7.15 handling persistence exceptions

Try{... CTX. savechanges ();}Catch(UpdateexceptionEx) {log. writeerror (ex. stateentries, Ex. innerexception );}

It is easy to handle errors. We recommend that you put savechanges in a method and call it each time it is persisted. In this way, you do not need to write a try/Catch Block every time you save the data.

You must know how to send custom commands to the database to update data in the next feature of persistence.

7.4.2 execute custom SQL commands

EF can persist any modification, but in some cases it is easier to use a custom SQL command than to use EF. Let's take a look at how custom SQL commands in the orderit application can help.

In orderit, there is always a zero inventory item. This value is not updated when a new product is added or sold. This is because in Chapter 5th, you map the availableitems attribute to the availableitems column of the product table and set the attribute to computed. That is to say, this attribute has never been used when the ing column is updated in the database. When the object is persisted, the value of the computed column is directly queried from the database and placed into the attribute.

Essentially, this method eliminates the need to update available items by entrusting updates to a database or using custom SQL commands like stored procedures. It is necessary to calculate the value of the available items correctly in this method.

To correctly calculate available items, You need to modify the code written earlier. Add the following operations:

    1. When creating a product, let the context create a line in the database, and then issue an SQL command to update the availableitmes column.
    2. When creating or updating an order, if the detail is new, an SQL command is issued to subtract the quantity sold from the inventory quantity; if the detail is removed, an SQL command is issued, add the sales quantity to the inventory quantity. If detail is sucked, issue an SQL command, subtract the old quantity from the inventory, and then add the new quantity.

Why? Why not let EF persist columns? There are two reasons: concurrency and conciseness.

    • Concurrency-Assume that two people create an order at the same time. At the same time, they both read the product data, and the first person updates the data. The second person then updates the expired data. Concurrent check can be a solution, but it will waste your time. The user should not re-insert the order because the inventory has changed.
    • Simplicity-Updating a product requires the product to be appended, even if foreign key Association is used. In addition, the availableitems attribute and all entity states must be updated to cause more complex code. Manual updates are more direct, reducing complexity.

This method is quite simple. Before savechanges is called, obtain all the details in the modified state and add the quantity to availableitems. After savechanges, obtain all the entities in the added and modified states, and subtract quantity from availableitems. Finally, add quantity to availableitems for each detail entity in the deleted state.

Execute custom SQL commands and use the executestorecommand METHOD OF THE objectcontext class. This method has the same functions as the executestorequery <t> method in Chapter 4.

Listing 7.16 execute a custom SQL command to update data

 
CTX. executestorecommand ("UpdateProductSetAvailableitems = availableitems-3WhereProductid = 1");

I learned in Chapter 4 that it is not a good idea to embed SQL in program code, because you need to bind your program to the specified database. This is not a problem in most cases, but stored procedures are more desirable. In Chapter 2, you will learn how to replace the previous code with stored procedures.

This chapter ends, and the next chapter will learn how to process concurrency and transactions.

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.