Using the Entity Framework

Source: Internet
Author: User
Tags management studio sql server management studio connectionstrings

ORM and EF

When we want to develop an application, we need to think about how to present the data and how to persist it. The most important thing to consider when considering this problem is the performance of the program, the simplicity of development, and the maintainability and extensibility of the code.

Persistence (persistence) is the mechanism by which individual processing state information can be persisted in an application indefinitely. If this mechanism is not persisted, the state can only be stored in memory and the machine will be lost after it is shut down.

In the application, when we want to persist the data, we select the relational database (Relation), and when we want to save the data temporarily, we use the objects stored in memory. Currently, for most developers, relational database technology is used as a persistence mechanism. While some people are now trying to use object database technology, relational database technology remains the primary persistence mechanism for many years.

Why does the object database appear? SQL language is a non-procedural set-oriented interpretation language, and many high-level languages are procedural object-oriented compiler language, which makes the mismatch between the two languages, resulting in less efficient. This mismatch is called "Impedance mismatch" and the object database is designed to solve "impedance mismatch".

We know that in relational database technology, data is stored and organized using table in the structure of rows and columns. Before. NET 2.0, when C # had no generics, people were basically mapping and storing data that was queried from a relational database using a DataTable populated in a dataset, as shown in the following code:

using (SqlConnection conn = new SqlConnection (connstring)) {    using (SqlDataAdapter da = new SqlDataAdapter ("SELECT * F Rom order ", conn)) {        datatable dt = new DataTable ();        Da. Fill (DT);        ...    }}

While this approach allows object-oriented languages to match relational databases, it has some obvious drawbacks, such as non-type security, difficult manipulation, low performance, and so on. Starting with. NET 2.0, people began to match data in relational databases with a collection of entity model objects using generic technology, which solves the shortcomings of the DataTable approach, and it has the characteristics of strong typing, auto-completion in VS, compile-time checking, etc. NET Developer's favorite.

In order for developers not to do this "match" work manually, many ORM tools (such as entity Framework, nhibernate, etc.) have been developed. The ORM (Object Relation Mapping) tool, as its name implies, is designed to solve the "mismatch" between "relational" and "object-oriented", which allows developers to spend more time focusing on the business without being overly concerned about the persistence layer.

The entity Framework (EF) is an ORM solution developed by Microsoft on the basis of ADO, based on the entity Data Model (EDM). EF leverages the abstraction of data structures to convert each database object into a class object (Entity) in the application, and the data fields are converted to properties, and the relationships are converted to associative attributes (association), so that the database's e/r The model is completely turned into an object model, so that developers can invoke access with a familiar object-oriented programming language. EF 4.0 supports database first, model first, and code three generation modes, with more people in code first mode.

Concepts and theoretical things are not much to say, I am also with questions to find the network resources according to their own understanding of the semi-partial summed up, and my humble, many things want to describe but do not know how to organize the language.

The purpose of this paper is to let the reader have a perceptual understanding of EF, and then understand the application of EF in ASP.

Using the Entity Framework

Then in the previous blog post, using Ninject, we are now going to change the manual data in the code to read from the database. To do this, we first prepare the database. This example uses MS SQL Server, which is the same with other databases. Create a database named bookshop first, and then execute the following script to create a books table:

CREATE TABLE Books (     [ID] INT NOT null PRIMARY KEY IDENTITY,     [Title] NVARCHAR (+) not NULL,    [ISBN] VARCHAR (20 ) not NULL,     [Summary] NVARCHAR (+) not NULL,    [Author] NVARCHAR (.) not NULL,    [Thumbnail] VARBINARY (MAX), C6/>[price] DECIMAL (2) not NULL,    [Published] DATE not NULL,)

Then add a few data to the table for testing:

Next we're going to have the application connect to the database. Because the last blog post I wrote in the company at the time of rest, the company's computer is loaded with VS2010, the home notebook is VS2012, so we have to re-move the example of the previous blog post to VS2012, for this example, VS2010 and VS2012 are the same. The directory structure of the previous example project is as follows:

The example in this article will continue on the basis of this example in the previous article.

Use NuGet to install the Entity Framework package in the Bookshop.domain project, refer to the previous article in this series.

Add a class named Efdbcontext in the concrete folder of the Bookshop.domain project, with the following code:

public class Efdbcontext:dbcontext {public     dbset<book> Books {get; set;}}

The first step in using EF Code is to create a class that inherits from System.Data.Entity.DbContext, which defines a property for each table in the database, and the name of the property represents the table name in the database. Dbset, as the return type, is the appliance used to generate crud (Create, Read, update, and delete) operations that map rows of database tables.

We need to add a connection string to the database in the Web. config configuration file in the Bookshop.webui project to tell EF how to connect to the database. Configure the connection string according to the database on your machine as follows:

<connectionStrings>  <add name= "Efdbcontext" connectionstring= "Data source=.\sqlexpress;initial Catalog=bookshop; User Id=sa; Password=sa "Providername=" System.Data.SqlClient "/></connectionstrings>

Next, we will transform the Bookrepository class file in the concrete file under the Bookshop.domain project, and change the manually crafted data from the code to read from the database to test whether the application can properly connect to the database. The modified Bookrepository class is as follows:

public class Bookrepository:ibookrepository {    private Efdbcontext context = new Efdbcontext ();    Public iqueryable<book> Books {        get {return context. Books; }    }}

In our warehousing class, we use EF to get the data in the database by creating an instance of the Efdbcontext class. As you can see, we do not need to write our own ADO code to connect and read the database, very simple and clear, this is how we use the Entity Framework. Let's look at the effect of the operation:

Here we have successfully used EF to connect to the database and read out the data from the database. We can also make very flexible queries through LINQ, just like writing SQL. For example, to query the first 10 records of the price below 100 yuan, and the price from low to high display, then we can be in the Bookshop.webui project under the list method in the Bookcontroller to write:

Public ViewResult List () {    return View (repository. Books        . (b = b.price)        . Where (b = B.price <)        . Take (10));}

Maybe you'll soon have a question about how EF gets the database: EF reads the entire books table's data into memory from the database, and then returns it to the caller (repository in the code above.) Books) using LINQ statements to filter the first 10 data that the user wants, if there are millions of data in the Books table, isn't that memory a dead end and EF's not that stupid? Will EF intelligently generate SQL text based on LINQ query statements and then query the data in the database? It's about IQueryable and IEnumerable.

IQueryable and IEnumerable

In fact, for the above-described Conditional query LINQ statement, EF is to read the entire books table data in the database to memory, or according to the LINQ query Statement intelligent Generation of SQL and then execute the query, the full coder to decide. We open the Bookrepository class file for the Bookshop.domain project, notice the return type of the books property in the class:

IQueryable<Book> Books {    get {return context. Books; }}

In our previous blog post, we raised a question about using IQueryable as the return type: Why use IQueryable instead of IEnumerable as the return type? The answer is: Using IQUERYABLE,EF will be based on the caller's LINQ expression into the corresponding SQL query statement, and then to the database to execute the query, the query is the data that the user wants, and the use of IENUMERABLE,LINQ expression filtering, Operations such as sorting occur in memory, where EF first queries the entire table's data from the database, and then the caller uses LINQ statements to filter, sort, and so on. Isn't that so? Let's watch for two things. The SQL statements generated by EF are known.

Let's take a look at the use of IQueryable. Rerun the program, then use the SQL Server Management Studio activity and monitor to see the SQL statements executed by our bookshop application, as follows:

It turns out that using IQUERYABLE,EF is the first way to generate a corresponding SQL statement based on a LINQ expression before executing a query.

Let's just change the code a little bit to see what happens with IEnumerable. Modify the Bookrepository class as follows:

public class Bookrepository:ibookrepository {    private Efdbcontext context = new Efdbcontext ();    IEnumerable<Book> Books {        get {return context. Books; }    }}

Of course, the Ibookrepository interface implemented by the Bookrepository class (in the abstract folder of the Bookshop.domain project) also needs to be changed:

Public interface Ibookrepository {    IEnumerable<Book> Books {get;}}

Run the application again and view the last executed SQL statement with activity and monitor such as:

We see that when we switch to IEnumerable, the SQL generated by EF does not have any filtering, sorting, and so on, it selects all the data in the table at once, and the LINQ expression written above doesn't matter.

IQueryable Although it is possible to generate the appropriate SQL statements intelligently based on a LINQ expression, there is a process for parsing LINQ expressions that is relatively poor in performance compared to IEnumerable. So when do we use IEnumerable, when do we use IQueryable? I think, for a small amount of data (such as from the database to read application-related system information) and do not need to filter the data, the use of IEnumerable is more appropriate, for large amounts of data need to filter data (such as paged query), the use of IQueryable is more appropriate.

Reference:
Pro ASP. NET MVC 4
http://www.entityframeworktutorial.net/

Using the Entity Framework

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.