Entityframework learning notes 4-Entity Data Model and addition, deletion, and modification operations

Source: Internet
Author: User

Next we will build a simple example to learn the EF framework and go directly to the topic:

I. Create an Object Data Model

1. Create a console application named efdemo

2. Create an entity model

On the efdemo project, right-click Add-new item-Select data-ADO. Net object model from the installed options, and name it efstudy.

3. Connect to the database

After step 2 is completed, a wizard will pop up. Select "generate from database" and click "create connection ..." Click, select SQL Server, and click Next. After the connection test is successful, confirm to return. Pay attention to the app below. config will automatically generate a database name + entities name, which will become the context class name. We recommend that you change it to *** + context, such as popcontext, and then click Next.

4. Specify the corresponding database tables, views, and stored procedures to generate objects.

Select the corresponding database tables, views, and stored procedure to generate objects, and click Finish.

Note: You can use the following statements to create a simple table in the SQL Server database in advance.

Create Table [DBO]. [sysdept] (
[ID] [varchar] (16) primary key,
[Name] [varchar] (64) not null
)
Go

After completing the preceding steps, add the efstudy. edmx file in the project and display the sysdept class in a graphical manner.

Ii. add, delete, and modify operations

1. Add

Because the console application was created before, and only one table was introduced for clarity, and the code was simplified and directly written in program. CS.

Static void main (string [] ARGs) {// Add insertdept ();} Private Static void insertdept () {// The database table sysdept has been mapped by EF to the sysdept class // this can be used directly to define the object sysdept = new sysdept (); // set the attribute sysdept for the object. id = "1"; sysdept. name = "Yantai ** Company"; // EF has created a context object. The class name is popcontext context = new popcontext () specified in the object type creation stage (); // Add the sysdept object to the context object. // method 1 (recommended) context. sysdept. addobject (sysdept); // method 2 // context. addtosysdept (sysdept); // method 3 // context. addobject ("sysdept", sysdept); // After the preceding operation, the data is changed to the memory. perform the following operations and save the operation to the database int I = context. savechanges (); console. writeline ("affected rows:" + I );}

As shown above, there are three ways to add an object to a context object. The first method is recommended, which conforms to the Conventions and nature. The second method is difficult to find when there are many database tables, the third is that the first parameter uses a string, which is easy to spell and tedious.

Use the SQL Server Profiler (START-SQL Server 2008-) performance tool that comes with SQL server. If you cannot find the tool, the SQL Server version you have installed is express, this tool is available for both the development and enterprise editions). You can view each SQL statement executed by the database, that is, you can observe the execution of the above program, EF converts object operations in the program to specific SQL statements, which is helpful for understanding and learning at the initial stage and Performance Tuning in later multi-Table Association.

 

2. Delete

To delete a record, you must first find the record. There are two methods: one is to define a new object and add the object to the management through the attach method of context, as shown in the following code, the second is to search in the context object. The code is reflected in the modification example.

Private Static void deletedept () {// first define a new object and set the primary key attribute sysdept = new sysdept (); sysdept. id = "1"; // attaches this object to the context object popcontext context = new popcontext (); context. sysdept. attach (sysdept); // remove an object. Two Methods: // method 1. context is recommended. sysdept. deleteobject (sysdept); // context. deleteobject (sysdept); // method 2 // After the above operation, the data is changed to the memory. Execute the following operations and save the operation to the database int I = context. savechanges (); console. writeline ("affected rows:" + I );}

Searching for information on the internet found that there are many of the following two methods, which may be supported in earlier versions and are outdated in ef5.0. Context neither has the entry method nor the Remove Method, sysdept. the entitystate attribute is read-only and cannot be set.

1. Context. Entry (sysdept). State = entitystate. Deleted; // The entitystate enumeration value must be using system. Data;
2. Context. sysdept. Remove (sysdept)

3. Modify

To modify a record, you must first find the record

 

Private Static void updatedept () {// find the record to be modified. The search parameter is a Lamda expression. Learn more about popcontext context = new popcontext (); sysdept = context. sysdept. firstordefault (Dept => Dept. id = "1"); // modify the property sysdept. name = "Qingdao ** Company"; // After the preceding operations, the data is changed to the memory. After the following operations are performed, the data is saved to the database int I = context. savechanges (); console. writeline ("affected rows:" + I );}

 

This shows the second way to search for records. In fact, it is more common to find an object and then delete or modify it.

Similarly, ef5.0 does not have context. Entry (sysdept). State = entitystate. modified.

4. Transaction Processing

As mentioned above, adding, deleting, and modifying transactions are often used in programs, which is similar to do.net.

Private Static void transaction () {popcontext context = new popcontext (); idbtransaction trans = NULL; try {// open the connection context. connection. open (); // start transaction trans = context. connection. begintransaction (); // execute the operation // modify the sysdept = context. sysdept. firstordefault (Dept => Dept. id = "1"); sysdept. name = "Linyi **** Company"; // Add a record sysdept = new sysdept {id = "2", name = "Heze *** Company"}; context. sysdept. addobject (sysdept); // save it to the database int I = context. savechanges (); // submit the transaction trans. commit (); console. writeline ("successfully executed, affected rows:" + I);} catch (exception ex) {TRANS. rollback (); console. writeline ("exception occurred, rolled back" + ex. message);} finally {context. connection. close ();}}

The above process is submitted normally for the first time, and sysdept. name = "Linyi ***** Company"; Change "Linyi" to "Rizhao" in "Linyi". If you execute this operation again, the system will exit due to an exception caused by repeated primary key insertion, not only is new data not inserted, but the data modified before the data is inserted is not saved to the database, which means the rollback function is implemented.
Note: rollback is only valid for the database. The "Linyi *** company" in the popcontext object in the memory has been changed. rollback does not restore the data in the memory to the pre-transaction state.

Iii. Summary
This section shows the advantages of ORM. in the program, you do not need to write the insert/delete/update SQL statement corresponding to the database, especially when there are many table fields, writing a long insert statement is prone to misplacement or missing problems. On the other hand, you can directly instantiate the object and obtain or set the attribute values, smart prompts are friendly and convenient.

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.