Entity Framework 4 in action Reading Notes -- Chapter 7: Persistent Object to database: persistently modified object to database

Source: Internet
Author: User
7.2 persistently modified entities to the database

There are three ways to persist a single object to a database:

    • Persistence is a new line.
    • Use attributes to update an existing row.
    • Use Key properties to delete an existing row.
7.2.1 persistence as a new line

First, add a customer. Very simple: Use the addobject method to pass a customer instance and then call savechanges.

 VaR Cust = New  Customer {Name = "Stefano mostarda" , Billingaddress = New  Addressinfo () {Address = "5th Street" , City ="New York" , Country = "USA" , Zipcode = "0000000" }, Shippingaddress = New  Addressinfo () {Address = "5th Street" , City = "New York" , Country = "USA" , Zipcode = "0000000" }, Wsenabled = True , Wsusername = "User1" , Wspassword ="User1pwd" }; CTX. Companies. addobject (Cust); CTX. savechanges ();

Because the primary key attribute is identity, you do not need to set its value. If it is set, the value is ignored.

If the key is not an identity, you need to set it. Otherwise, an invalidoperationexception occurs during the runtime.

It is not difficult to persist a new object. Even if the persistence process involves complex types, the context can be well processed.

7.2.2 Persistent modification to existing entities Persistent connection

Connection refers to modifying the entities retrieved from the database in the same context. In this case, you can modify the attributes and then call the savechanges method.

VaRCust = CTX. Companies. oftype <Customer> (). First (C => C. companyid = 1); Cust. Name ="Stefano mostarda"; CTX. savechanges ();

Because State Manager tracks the original and current values of object properties, SQL only affects the modified attribute ing columns. When modifying the scalar attribute of a complex type, all attributes of the complex type are persistent. For example, if you modify the shipping address, SQL updates the shipping city, country, and zip codes even if they are not modified.

Persistence when disconnected

Assume there is a method that receives a customer instance as a parameter. You create a new context, attach the customer, and then persist it. The problem arises. When you attach an object to the context, it is in the unchanged state, and savechanges will not persist anything.

There are two ways to solve this problem:

    • Append the passed object and use the changeobjectstate method to modify its status to modified.
    • Query the database to retrieve the object, and then use the applycurrentvalues method to overwrite the attribute of the database object with the property of the input object.

The first method is the simplest and most commonly used method.

VoidUpdatecustomer (CustomerCust ){Using(VaRCTX =NewOrderitentities() {CTX. Companies. Attach (Cust); CTX. objectstatemanager. changeobjectstate (Cust,Entitystate. Modified); CTX. savechanges ();}}

The disadvantage of this method is that changeobjectstate marks the object and all its attributes are modified. As a result, the update command modifies all ing columns even if they are not modified. If no value is set for an attribute, the value in the database will be overwritten, resulting in data loss.

Let's take a look at the example. Assume that there is a customer with ID 1. You have created a customer instance and set companyid to 1 and name to newname. Then it is appended to the context, marked as modified, and savechanges is called. The generated update command updates the name column, and other columns also use their default values (the string is null, the integer is 0, and so on ). That is to say, the data in the database before the customer is lost. This problem is explained:

The second method is simple even if it is a little more complex than the first method.

For the second method, query the database to retrieve the object to be modified, and then use the applycurrentvalues method to apply the modified object value. Finally, savechanges is called. When the modification is made persistent, the optimal SQL statement is generated because the state manager knows which attribute has been modified.

 
VoidUpdatecustomerwithapplycurrentvalues (CustomerCust ){Using(VaRCTX =NewOrderitentities() {CTX. Companies. oftype <Customer> (). First (C => C. companyid = Cust. companyid); CTX. Companies. applycurrentvalues (Cust); CTX. savechanges ();}}

Unfortunately, applycurrentvalues and changeobjectstate have the same problem because the current value of the entry is overwritten using the value of the passed object. If the attributes of the input object are not set, data will be lost as a result.

Applycurrentvalues has another problem. It involves two round-trips to the database: one reading data and the other updating data. This will cause performance loss. Especially when data involves multiple tables, this problem becomes more and more serious. Take the orderit example as an example. The Query Needs to associate multiple tables. Changing the attributes also affects one or more tables. If you have high performance requirements, you may need to select the changeobjectstate method, because the update process only needs to operate the database once.

Finally, both methods work in some situations, but misuse may lead to data loss. If you know that some attributes are not set in advance, you can set them in two ways:

    1. Retrieve a customer from a database and manually modify its attributes one by one based on the input object values.This method works well because it is similar to connection conditions.
    2. Append the input object to display the attributes marked for update.This method eliminates the risk of retrieving objects and data loss in the database.

The second method is the best. It requires someCodeBut it is very effective because it provides the best performance while avoiding data loss.

Select the attribute to be updated when the connection is disconnected.

Update the name and address of the customer. To this end, you can create a method that attaches an object and marks the specified attribute as modified. This marking process also automatically sets the entity to the modified state. When the savechanges method is called, only the specified attributes are persisted to the database.

The method for marking an attribute as modified is setmodifiedproperty. It only receives one parameter, indicating the name of the attribute to be updated.

VaREntry = OSM. getobjectstateentry (customer); entry. setmodifiedproperty ("Name"); Entry. setmodifiedproperty ("Shippingaddress"); Entry. setmodifiedproperty ("Billingaddress");
Persistent Object Deletion

It is very easy to delete an object. Call the deleteobject method and pass in an object to mark the object as deleted. Then, savechanges is called. Remember, before being marked as deleted, the object must be appended to the context.

Delete connections

 
VaRCust = CTX. Companies. oftype <Customer> (). First (); CTX. deleteobject (Cust); CTX. savechanges ();

Delete a connection

VaRCust =NewCustomer() {Companyid = ID}; CTX. Companies. Attach (Cust); CTX. deleteobject (Cust); CTX. savechanges ();

Now we can modify the customer data as needed, but this is just the beginning. The persistence of associated entities will be involved below.

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.