Entity Framework Quick Start-direct modification (brief introduction to objectcontext Processing Mechanism) [reprint]

Source: Internet
Author: User
Entity
Framework Quick Start -- directly modify (brief introduction to objectcontext processing mechanism)

Before introducing how the Entity Framework modifies an object to a database, let's briefly introduce the processing mechanism of objectcontext.

1. objectcontext Processing Mechanism

Objectcontext is entity
Framework encapsulates the context of database access and metadata information of ing relationships between entities. EF helps us encapsulate such a unified interface. All of our operations can be performed by adding, deleting, querying, modifying, and other operations on the corresponding database only through this entity context. Of course, we need to understand the SQL generation mechanism of EF so that we can better use EF to help us generate more efficient SQL scripts.

Let's look at an example: Project and entity model diagram (a simple example)

Then read the following code:

Static void main (string [] ARGs)
{
Schooldbentities schooldb = new schooldbentities ();
Student = new student ();
Student. Address = "Beijing Shangdi ";
Student. Name = "feilong ";
Student. Phone = "110 ";
Schooldb. Student. addobject (student );
Schooldb. savechanges ();
}

Add a piece of data to a simple online database. We add a breakpoint in the red background of the above Code [schooldb is the context that EF automatically generates for us to inherit from objectcontext] and perform quick monitoring on schooldb. As follows:

Due to the limited length of the image, only some views are captured. Here I will briefly introduce several key attributes.

(1): connection. I believe you can guess it all at once. Of course, it encapsulates xxxconnection (for example, sqlconnection) of the EF database ). This will not be too long.

(2): objectstatemanage, which is responsible for maintaining the object status and identity management for entity-type instances and relational instances. It is also an important attribute in EF context. It helps us put the added entities in the Add queue, put the modified entities in the modified queue, and delete the modified entities. When each object is modified, EF helps us put the object in the corresponding queue and modify the state of the corresponding object (entitystate). When the savechanges () method of objectcontext is called, EF generates the final SQL script based on the queue situation and edmx metadata ing information.

(3): we can see that _ addedentitystore is a set of entities we just mentioned, and each object corresponds
Entitystate (indicating the state of the entity in memory, which is an Enum type) is in the added state. Of course, this indicates that the addition is performed. When an SQL statement is generated, it is insert...
Of course, there are also deleted queues and modified queues. Let's just take a look.

(4): entitystate, the state of the object. Mark the operations that our developers perform on the object. The following table describes the status and description of the object (from msdn)

Member name Description
Detached The object exists but is not tracked. The object is in this State after it is created but before it is added to the object context. An entity is also in this state
After it has been removed from the context by calling the detach method or if it
Is loaded by using a notrackingmergeoption. There is no objectstateentry instance and the status is detached
Object Association.
Unchanged This object has not been modified since the object is appended to the context, or since the savechanges method was called last time.
Added The object is a new object and has been added to the object context, but the savechanges method has not been called. After saving the changes, the object state changes to unchanged. Status:
The added object does not have the original value in objectstateentry.
Deleted The object has been deleted from the context of the object. After saving the changes, the object state changes to detached.
Modified A scalar attribute on the object has been changed, but the savechanges method has not been called. Call detectchanges in a poco object without a change tracking proxy
Method, the status of the modified attribute is changed to modified. After saving the changes, the object state changes to unchanged.

Note:

The object context must know the object status to save the changes back to the data source. Objectstateentry object stores entitystate information. The savechanges method of objectcontext processes the entity appended to the context and updates the data source based on the entitystate of each object. For more information, see adding, modifying,
And deleting objects.

The object status in the object context is managed by objectstatemanager. To find the object status, call one of the following objectstatemanager Methods: trygetobjectstateentry, getobjectstateentry, or getobjectstateentries. The state attribute of objectstateentry defines the State of the object.

Summary:

EF is directly maintained by modifying the entity for developers.
Object operation set in the objectcontext instance and modify the status of a single object. The final result is generated based on the set and status plus the metadata information mapped to the object in the table above.
SQL script. Therefore, when you operate on multiple objectcontext instances, you must note that when you call the instance's own savechanges () method, it only maps the operations on the memory space of its own instance back to the database, changes to object sets in other objectcontext instances are not affected. In addition, EF automatically performs cache processing. When we first query an object, it automatically extracts data from the database and assembles the data into Entity classes for our developers, when the same data is obtained for the second time, it will first find the data from the cache. If the data already exists, it will return immediately and will not query the database. This causes a problem. If the objectcontext instance is not destroyed, its cache will continue to expand. Therefore, when developing an application, it is not appropriate to directly process the context of EF in a single instance. The best way is
You can use the same objectcontext instance in one request processing (web development) to avoid maintenance of multiple context instances, and avoid the increasing expansion of context instances.

 

2. EF entity Modification

How can we modify the subject only now?

Method 1 is not recommended:

Idea: First retrieve the object from objectcontext, then assign the DTO attribute passed by the foreground to our object, and then call the objectcontext's guaranteed modification method.

However, this method is the least recommended, because the data must be checked out before each modification and tracked by sqlprofiler. Such an operation requires two connections to the database. This is intolerable!

Recommended Method 2:

Idea: you do not need to first find the entity because we know that EF passes
Objectstatemanage controls the status of adding, modifying, and deleting queues and entities. All of us can directly convert DTO into entities, and then convert the queues corresponding to entities, in addition, we manually process the state of the object and then call the objectcontext modification method to avoid the problem of querying and modifying the object first, and connecting the database twice. The instance code is as follows:

 

Static void main (string [] ARGs)
{
Schooldbentities schooldb = new schooldbentities ();
// Assume that studentdto is transmitted over the network to convert the DTO into a database entity.
Student = new student ();
Student. ID = 1; // assume that the primary key must exist for the value passed by DTO. Otherwise, an error is returned.
Student. Address = "Beijing Shangdi 1 ";
Student. Name = "feilong 1 ";
Student. Phone = "1101 ";

// First attach the object to the object context
Schooldb. Student. Attach (student );
// Manually modify the object status
Schooldb. objectstatemanager. changeobjectstate (student, entitystate. modified );
// Save it back to the database
Schooldb. savechanges ();
}

The description is complete! Hope to be useful to beginners! You are welcome to correct the error!

 

Technology changes the world and strives to change life!

Entity
Framework Quick Start-index stickers

Before introducing how the Entity Framework modifies an object to a database, let's briefly introduce the processing mechanism of objectcontext.

1. objectcontext Processing Mechanism

Objectcontext is entity
Framework encapsulates the context of database access and metadata information of ing relationships between entities. EF helps us encapsulate such a unified interface. All of our operations can be performed by adding, deleting, querying, modifying, and other operations on the corresponding database only through this entity context. Of course, we need to understand the SQL generation mechanism of EF so that we can better use EF to help us generate more efficient SQL scripts.

Let's look at an example: Project and entity model diagram (a simple example)

Then read the following code:

Static void main (string [] ARGs)
{
Schooldbentities schooldb = new schooldbentities ();
Student = new student ();
Student. Address = "Beijing Shangdi ";
Student. Name = "feilong ";
Student. Phone = "110 ";
Schooldb. Student. addobject (student );
Schooldb. savechanges ();
}

Add a piece of data to a simple online database. We add a breakpoint in the red background of the above Code [schooldb is the context that EF automatically generates for us to inherit from objectcontext] and perform quick monitoring on schooldb. As follows:

Due to the limited length of the image, only some views are captured. Here I will briefly introduce several key attributes.

(1): connection. I believe you can guess it all at once. Of course, it encapsulates xxxconnection (for example, sqlconnection) of the EF database ). This will not be too long.

(2): objectstatemanage, which is responsible for maintaining the object status and identity management for entity-type instances and relational instances. It is also an important attribute in EF context. It helps us put the added entities in the Add queue, put the modified entities in the modified queue, and delete the modified entities. When each object is modified, EF helps us put the object in the corresponding queue and modify the state of the corresponding object (entitystate). When the savechanges () method of objectcontext is called, EF generates the final SQL script based on the queue situation and edmx metadata ing information.

(3): we can see that _ addedentitystore is a set of entities we just mentioned, and each object corresponds
Entitystate (indicating the state of the entity in memory, which is an Enum type) is in the added state. Of course, this indicates that the addition is performed. When an SQL statement is generated, it is insert...
Of course, there are also deleted queues and modified queues. Let's just take a look.

(4): entitystate, the state of the object. Mark the operations that our developers perform on the object. The following table describes the status and description of the object (from msdn)

Member name Description
Detached The object exists but is not tracked. The object is in this State after it is created but before it is added to the object context. An entity is also in this state
After it has been removed from the context by calling the detach method or if it
Is loaded by using a notrackingmergeoption. There is no objectstateentry instance and the status is detached
Object Association.
Unchanged This object has not been modified since the object is appended to the context, or since the savechanges method was called last time.
Added The object is a new object and has been added to the object context, but the savechanges method has not been called. After saving the changes, the object state changes to unchanged. Status:
The added object does not have the original value in objectstateentry.
Deleted The object has been deleted from the context of the object. After saving the changes, the object state changes to detached.
Modified A scalar attribute on the object has been changed, but the savechanges method has not been called. Call detectchanges in a poco object without a change tracking proxy
Method, the status of the modified attribute is changed to modified. After saving the changes, the object state changes to unchanged.

Note:

The object context must know the object status to save the changes back to the data source. Objectstateentry object stores entitystate information. The savechanges method of objectcontext processes the entity appended to the context and updates the data source based on the entitystate of each object. For more information, see adding, modifying,
And deleting objects.

The object status in the object context is managed by objectstatemanager. To find the object status, call one of the following objectstatemanager Methods: trygetobjectstateentry, getobjectstateentry, or getobjectstateentries. The state attribute of objectstateentry defines the State of the object.

Summary:

EF is directly maintained by modifying the entity for developers.
Object operation set in the objectcontext instance and modify the status of a single object. The final result is generated based on the set and status plus the metadata information mapped to the object in the table above.
SQL script. Therefore, when you operate on multiple objectcontext instances, you must note that when you call the instance's own savechanges () method, it only maps the operations on the memory space of its own instance back to the database, changes to object sets in other objectcontext instances are not affected. In addition, EF automatically performs cache processing. When we first query an object, it automatically extracts data from the database and assembles the data into Entity classes for our developers, when the same data is obtained for the second time, it will first find the data from the cache. If the data already exists, it will return immediately and will not query the database. This causes a problem. If the objectcontext instance is not destroyed, its cache will continue to expand. Therefore, when developing an application, it is not appropriate to directly process the context of EF in a single instance. The best way is
You can use the same objectcontext instance in one request processing (web development) to avoid maintenance of multiple context instances, and avoid the increasing expansion of context instances.

 

2. EF entity Modification

How can we modify the subject only now?

Method 1 is not recommended:

Idea: First retrieve the object from objectcontext, then assign the DTO attribute passed by the foreground to our object, and then call the objectcontext's guaranteed modification method.

However, this method is the least recommended, because the data must be checked out before each modification and tracked by sqlprofiler. Such an operation requires two connections to the database. This is intolerable!

Recommended Method 2:

Idea: you do not need to first find the entity because we know that EF passes
Objectstatemanage controls the status of adding, modifying, and deleting queues and entities. All of us can directly convert DTO into entities, and then convert the queues corresponding to entities, in addition, we manually process the state of the object and then call the objectcontext modification method to avoid the problem of querying and modifying the object first, and connecting the database twice. The instance code is as follows:

 

Static void main (string [] ARGs)
{
Schooldbentities schooldb = new schooldbentities ();
// Assume that studentdto is transmitted over the network to convert the DTO into a database entity.
Student = new student ();
Student. ID = 1; // assume that the primary key must exist for the value passed by DTO. Otherwise, an error is returned.
Student. Address = "Beijing Shangdi 1 ";
Student. Name = "feilong 1 ";
Student. Phone = "1101 ";

// First attach the object to the object context
Schooldb. Student. Attach (student );
// Manually modify the object status
Schooldb. objectstatemanager. changeobjectstate (student, entitystate. modified );
// Save it back to the database
Schooldb. savechanges ();
}

The description is complete! Hope to be useful to beginners! You are welcome to correct the error!

 

Technology changes the world and strives to change life!

Entity
Framework Quick Start-index stickers

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.