. NET developers can embrace Entity Framework (ef4.3 release !!!)

Source: Internet
Author: User
Tags what sql

Ef4.3 was officially released in February 9. Microsoft's EF team began to work hard in the last year and added an important feature in version 4.3: "database migration ". For the orm framework, the code first function is almost unattractive because few developers use the automatically generated and uncontrollable entity classes, which is not elegant enough. The ORM framework in Python and other languages has long had the code first function. For EF, it was previously databas first or model first, and code first came out in EF4, which is not perfect, the biggest disadvantage of this solution is that the maintenance of the database model is troublesome. After some fields of the object cannot be added or deleted, the table structure in the database can be easily updated, developers need to spend a lot of effort to maintain database structure upgrades and retain historical data, which is inconvenient during the development process. In this version 4.3, the database migration function was finally coming out of the box. Microsoft products have a special feature, which is difficult to use in the early stage. However, the better the product will be used later, the more similar products will be used. NET developers, I personally think it is time to study in depth and apply EF in actual projects. My team and I have already started.

 

Reading directory

1. New features in ef4.3

2. EASY database maintenance

2.1 environment Configuration

2.2 simplest application

2.3 custom database change rules

2.4 version backtracking and SQL script generation

3. Outlook EF5

4. Summary

 

1. New features in ef4.3

1. database migration: This is the most important new feature in ef4.3, so that we can focus onProgramWhat do people like to do: Write simple and traditional CLR entities (plain old CLR object), instead of writing SQL statements to maintain the database. If you want to add a field, add it. If you want to delete it, delete it, is it nice to modify the name?

2. delete the edmmetadata table: This table is a semi-finished product. codefirst does not use this table to maintain the database. Because of the database migration function, the structure information of the database can be automatically generated, therefore, this table is redundant.

3. You can also add data description attributes for non-public fields: in the past, by default, code first will ignore attribute information on private, protected, and internal fields, even if you writeCodeWhen these fields are included in your model (using fluent api), the attribute information of these fields will also be ignored. In this version, if you use fluent API to add these non-public fields to your model, all attribute information will work.

4. more settings can be made in the configuration file: in APP/web. in the config file, you can perform more configuration for the code first method. For example, you can set the default database connection factory and database initialization, or even set the object constructor parameters in the configuration file. More configuration information can be found in the official blog.

5. modified a series of bugs, including the Unicode dbset name.

 

2. EASY database maintenance

Download the following sample code

2.1 environment Configuration

Name Description
Vs2010 Because nuget is used
Nuget The nuget command line tool is used for database migration. nuget is a very useful tool. If you haven't used this tool, you can go to Baidu or open-source communities to learn about it, it is best to upgrade to the latest version (I am 1.6 ).
Ef4.3 You can directly use nuget to install and reference it to your project. If you have installed the beta version, I believe you will also use the nuget command tool to upgrade it: Update-package entityframework

 2.2 simplest application Attempt

Software development is an iterative incremental process. No one can fully design the data model from the very beginning. Therefore, for code first, the most common development scenario is to constantly improve our data models with functional requirements. Next, we will try the database migration function step by step. In this example, I use the Asp.net mvc3 project. First, create a new project and select an empty template. By default, an entityframework will be referenced, but it may be version 4.1. Delete this reference, we use nuget to introduce EF of version 4.3 into mvc3:

 

Of course, you can also use the command line (Open nuget's package management console, PMC): PM> install-package entityframework

Suppose we want to build an online bookstore. First, we use code first to build our model:

  Public   class  bookcontext: dbcontext 
{< br> Public dbset books { Get ; set ;}
}< br> Public class book
{< br> Public int bookid { Get ; set ;}< br> Public string title { Get ; set ;}< br> Public double price { Get ; set ;}< BR >}

A very simple model. The next step is to use this model on our website to display the book in a list. The first step is to add homecontroller:

 
 Public ClassHomecontroller: Controller
{
PublicActionresult index ()
{
Bookcontext DB =NewBookcontext ();
DB. Books. Add (NewBook {Title ="Think in C ++", Price =59});
DB. savechanges ();
ReturnView (db. Books. tolist ());
}
}

Step 2 Add the corresponding View:

@ Model list <migarationdemo. Models. Book>
@{
Viewbag. Title ="Online Bookstore";
}

<H2> the bookstore contains the following books </H2>

<Ul>
@{
Foreach(VaRItemInModel ){
<Li> title: @ item. Title </LI>
}
}
</Ul>

Then F5, you should see the following results in the browser:

We have nothing to do, and a simple website is complete. Isn't it amazing? We didn't even configure the database connection string. This is because the EF design principle is "convention over configuration". By default, EF will look for the sqlexpress database on your local machine because I have this database on your machine, therefore, EF can automatically connect to the database and generate the corresponding database based on the above data model:

 
If everything is normal here, let's go to the topic and use the migaration function in ef4.3:

Step 1: modify our model. Due to new requirements, each book should also have an ISBN number:

  Public   class  book 
{< br> Public int bookid { Get ; set ;}< br> Public string title { Get ; set ;}< br> Public double price { Get ; set ;}< br> Public String ISBN {Get; set ;}
}

If you press F5 to run the system, an invalid operation exception occurs: "The model backing the 'bookcontext' context has changed since the database was created. consider using code first migrations to update the database (http://go.microsoft.com/fwlink? Linkid = 238269). "Prompt we should migrate the database.

It is very simple. You only need to execute the following three commands in PMC:

1. Enable-migrations

2. Add-migration book-ISBN (Book-ISBN is a name tag used to mark a migration point)

3. Update-Database

If you have executed the preceding three commands and everything goes well, congratulations! The Database Upgrade is complete and you should see in the project:

And the database has changed:

At this time, F5, the system should be running, everything should be normal, you can try to add another record in the controller, I added:

DB. Books. Add (NewBook {
Title ="Think in C ++ volumne two: practical programming",
Price =59,
ISBN ="978-7-111-17115-7"
});

Therefore, we can see that:

So far, we have completed the simplest database migration/upgrade step by step. In the migarations folder generated above, we mainly have a configuration file and a database migration file, the database migration file has two functions: Up (upgrading the database) and down (backtracking the database). You can easily understand the generated code.
 

2.3 custom database change rules

Although EF can automatically generate the corresponding database structure based on the data model, the automatically generated database is usually the most basic, and we usually need to set more attributes. For example, in the above book data model, the default database creates an index with the primary key bookid, but we also want to create an index with the title, so that we can quickly search by the title. In addition, in the above example, after the ISBN field is added, the existing data is null by default, which will cause unnecessary trouble in the program, we assume that we want the ISBN of the existing records to be 000-0-000-00000-0.

In the face of the above requirements, we first create a migration using the following command:

Add-migration indextitleanddefault

A new CS file is generated under the migrations folder in the project tree. My file is 201202191341050_indextitleanddefault.cs. Note that the previous timestamp will be different.

Then modify the generated migration file:

  Public   Partial   Class Indextitleanddefault: dbmigration
{
Public Override Void Up ()
{
Altercolumn ( " Books " , " Title " , C => C. String (nullable: False , Maxlength: 100 ));
Createindex ( " Books " , " Title " , True , " Index_title " );
Altercolumn ( " Books " , " ISBN " , C => C. String (nullable: False , Defaultvalue: " 000-0-000-00000-0 " ));

}

Public Override Void Down ()
{
Dropindex ( " Books " , " Index_title " );
}
}

Finally, execute the command: Update-database. The database should have the index of the title, and the default value of ISBN is000-0-000-00000-0.

 2.5 version backtracking and SQL script generation

All the operations above are updated to the latest version, but sometimes we want the database to be traced back to the previous version, which is difficult for manual database maintenance, the Database Change Feature provided by ef4.3 can be easily traced back:

You only need to add the-targetmigration: "XXX" parameter when executing the updat-database command. For example, if we want to return to the version in step 2, we only need to execute:

PM> Update-database-targetmigration: "201202368625099_book-isbn"

However, to implement version backtracking, we must pay special attention to implementing the down function, which is equivalent to the inverse function of the Down Function Type up function.

In addition, when executing the update-database command, add the-script parameter, instead of directly modifying the database structure, but generating the corresponding SQL script:

Update-database-script-sourcemigration: "AAA"-targetmigration: "BBB"

If targetmigration is not specified, it is migrated to the latest version by default.

3. Outlook EF5

According to Microsoft's Development Team, the next version of EF is EF5, and Microsoft's version number is very messy. At first, EF is 1.0, which will be followed later. net framwork has a uniform version, so it goes directly to EF4. the next version of Net Framework is 4.5, but EF has to become 5 again. What are they doing? In any case, EF5 is still worth looking forward to seeing this momentum, and there may be the following improvements:

1. enumeration types supported

2. Performance will be greatly improved

3. Improve the generation of SQL statements. Currently, the SQL statements generated by EF are complex and may be improved in the next version.

If you want EF to have any functions, you can go to their website to vote. Although the final decision is in Microsoft guy, your vote may affect the features they choose to develop first.

4. Summary

At present, EF is becoming an excellent ORM framework, which can greatly improve the development efficiency of programmers, free programmers from the data access layer, and focus on the business logic layer. Of course, to master EF well, you need to learn more deeply. For example, you should know what conventions it has and what SQL statements it generates for us, this helps us write efficient code.

 

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.