Entity Framework learning notes (3) ---- CRUD (2)

Source: Internet
Author: User

Please indicate reprinted address: http://www.cnblogs.com/arhat

Last night, the Old Wei's machine finally arrived, but after getting it back, everything was assembled. The only difference was a very important component, "power cord", Old Wei's sweat. So I borrowed a power cord from my friend and finally installed all the software and systems at two o'clock in the morning. This morning, I installed a MAC ). The most exciting thing about Old Wei is that he changed VS2013 and felt very good when using VS2013. The support for EF was actually greatly enhanced, you don't have to go to the Internet to find the plug-in. You can use the T4 file to generate a Context object class. Today, Old Wei uses VS2013 and SQL Server2008 to continue learning EF. As for the creation process, Old Wei has already introduced it in chapter 1, and the basic process is the same. In the first two chapters, Old Wei uses MySQL, so this chapter uses SQL Server, which is essentially the same. Old Wei imports MySQl Data into SQL Server.

Speaking of this, Old Wei has to mention that in the SQL Server Table Designer, many-to-many relationships cannot be established on tables. It is very unpleasant for Old Wei to create many-to-many relationships in the database graph! What makes Old Wei worse is that HeidiSQL cannot be used to establish a table relationship with SQL Server! Old Wei has crashed. If you have a better SQL Server Client tool, you can recommend it.

Now, let's start with this chapter! In the previous chapter, we just inserted, deleted, updated, and simply used the Where extension method to obtain data for the Clazz and Student tables. This chapter will further explain the operations on these two tables, because in this chapter, we mainly use the lazy loading of EF for data operations. Let's take a look at the first requirement in this chapter.

If we want to insert the students who change the class into the database when inserting the class, can this happen? The answer is yes. In fact, we already have such a requirement in our projects. Let's take a look at how to implement it with EF!

The code for changing Program. cs is as follows:

  Main(= =  Model.Student() { SName=,SAge=,SMail==  Model.Clazz() { CName=

When we do not find any problems, can we insert them into the data? Let's open the database to check the results and verify our conjecture.

Main (= Model. Student () {SName =, SAge =, SMail = Model. Clazz () {CName =

There are no problems with the same operation, but when we look at the data, we find the problem.

Main (= Model. student () {SName =, SAge =, SMail = context. clazz. where <Model. clazz> (c => c. CId = ). take <Model. clazz> (). firstOrDefault <Model. clazz> =

Run the command and find that there is no problem. When we view the data again, we find that the data is normal and there is no new record in the Clazz table (nonsense, because we found it !).

. (, (,. (), (), Feilong.com

Originally, EF is only used to operate databases more easily, so it must sacrifice a little efficiency. This does not need to be considered, and the current server configuration is so high, I don't care about the waste of memory.

What should we do if we want to update a student's class? Look at the Code:

  Main(= = context.Student.Where<Model.Student>(s=>s.SId==).Take<Model.Student>().FirstOrDefault<Model.Student>= context.Clazz.Where<Model.Clazz>(c => c.CId == ).Take<Model.Clazz>().FirstOrDefault<Model.Clazz>=

Run it and run it normally. The data has also won the same result. But now we have another problem. During the update process, we first query the problem and then update it to the database. In this way, we have operated the database twice, obviously it's not what we want, so how can we solve this problem, that is, we don't need to query it first and then update it? The answer is yes!

When talking about this problem, Old Wei has to say sorry here, because the content of the first two chapters is of MySql EF5, therefore, the content of EF6 in this section has slightly different advantages. So here, Old Wei uses the EF6 method.

For example, we have the following code:

  Main(= = = = = = = =

After a run, the data is always changed. What is the Entry here? According to Microsoft's explanation, "instances of the DbEntityEntry class provide access to information and control over entities tracked by DbContext. Use the context Entity or Entities method to obtain this type of object. "What do you mean? In fact, Entity Framworke updates the Entity to the database (add, delete, modify, and query), which is determined based on the Entity status, the Entity state is saved and set by the DbEntityEntry class object, but it also plays a very important role, that is, adding Entity (student here) to the context, if Entity is not in context, context cannot update data, so context. entry (Entity) is to add an object to the context for management, and change its status so that context can know how to process this Entity. when the SaveChanges method is called, context processes data according to the state.
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.

 

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. no ObjectStateEntry instance is associated with objects in the Detached state.
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. Objects in the state of Added do not have original values 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. When the DetectChanges method is called in a POCO object without a change tracking agent, the status of the Modified attribute is changed to Modified. After saving the changes, the object state changes to Unchanged.

 

The object context must know the object status to save the changes back to the data source. In this way, we can operate the database less once, but the primary key must exist in the database, which is hard to guarantee during program writing, therefore, we recommend that you use the original method. Of course, you should select different methods based on different situations. Some people recommend using EntityState, and some recommend using query update. For details, see the analysis, but here, Wei said that if we want to change some attributes of an object instead of all attributes, we have to use EntityState at this time.

Well, here we are talking about the CRUD operation of Entity Framework. It can only serve as an example. I hope you can get something from it!

Related Article

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.