[Path to ASP. net mvc] 06, asp. netmvc
Reference page:
Http://www.yuanjiaocheng.net/entity/createdatamodel.html
Http://www.yuanjiaocheng.net/entity/modelbrowser.html
Http://www.yuanjiaocheng.net/entity/dbcontext.html
Http://www.yuanjiaocheng.net/entity/entitytypes.html
Http://www.yuanjiaocheng.net/entity/entity-relations.html
I am also idle at home. Continue to write my [ASP. NET MVC mavericks road] series. In the previous blog of this series, when displaying the book information list, we manually created data in the program code. This document demonstrates how to use Entity Framework in ASP. net mvc to obtain data from a database. Although the title of this article sounds simple, if you read it carefully, I believe you will surely gain something.
Directory:
ORM and EF
To develop an application, we need to consider how to present data and how to persist data. What we need to care about when considering this issue is the performance of the program, the simplicity of development, and the maintenance and scalability of the Code.
Persistence refers to the Mechanism in which each processing state information can be permanently stored in an application. Without the persistence mechanism, the state can only be stored in the memory, and will be lost after the machine is shut down.
In applications, when we want to permanently save data, We will select relational DataBase. When we want to temporarily save data, we will use objects stored in the memory. Currently, most developers use relational database technology as a persistence mechanism. Although some people are currently trying to use the Object DataBase technology, the relational DataBase technology will remain the primary persistence mechanism for many years.
Why does the object database appear? SQL is a non-procedural set-oriented interpreted language. Many advanced languages are procedural object-oriented compilation languages, which make the two languages mismatched, this results in unsatisfactory efficiency. This type of mismatch is called "impedance mismatch". The emergence of the object database is to solve the "impedance mismatch ".
We know that in relational database technology, tables are used to store and organize data in rows and columns. In. before NET 2.0, when C # has no generics, people basically map and store the data queried from the relational database by filling in the DataTable in DataSet, as shown in the following code:
using (SqlConnection conn = new SqlConnection(connString)) { using (SqlDataAdapter da = new SqlDataAdapter("Select * from order", conn)) { DataTable dt = new DataTable(); da.Fill(dt); ... }}
Although this method can match relational databases with object-oriented languages, it has some obvious disadvantages, such as non-type security, difficult to control, and low performance. From. in the beginning of NET 2.0, people began to use the generic technology to match data in relational databases with the collection of entity model objects. This method solves the shortcomings of the DataTable method, in addition, it has the features of strong type, Automatic completion in VS, and compile-time check. net developers.
Many ORM tools (such as Entity Framework and nhib.pdf) have been developed to prevent developers from manually performing such "matching" tasks ). The ORM (Object Relation Mapping) tool, as its name implies, is used to solve the "mismatch" between "relationship" and "Object-Oriented ", it allows developers to spend more time focusing on their business without having to worry too much about the persistence layer.
Entity Framework (EF) is an ORM solution developed by Microsoft Based on ADO. NET. It focuses on Entity Data Model (EDM. EF converts each database object to an Entity object in an application using the abstract data structure, and converts data fields to properties ), the relationship is converted to Association, so that the E/R Model of the database is fully converted into an object model, so that developers can use the familiar object-oriented programming language to call access. Later than EF 4.0, it supports three generation modes: Database First, Model First, and Code First. The Code First mode has many users.
I will not talk much about concepts and theories. I also found network resources with questions and summarized them according to my own understanding, many things want to describe but do not know how to organize languages.
This article aims to give readers a perceptual knowledge of EF and then understand EF in ASP. net mvc applications will not study principles. I will introduce EF separately next time.
Use Entity Framework
Next, in the previous blog [ASP. net mvc mavericks road] 05-using Ninject, we need to change the manual data in the Code to read from the database. To this end, we need to prepare the database first. In this example, ms SQL Server is used, and other databases are used. First create a database named BookShop, and then execute the following script to create a Books table:
CREATE TABLE Books ( [ID] INT NOT NULL PRIMARY KEY IDENTITY, [Title] NVARCHAR(100) NOT NULL, [Isbn] VARCHAR(20) NOT NULL, [Summary] NVARCHAR(1000) NOT NULL, [Author] NVARCHAR(50) NOT NULL, [Thumbnail] VARBINARY(MAX), [Price] DECIMAL(16, 2) NOT NULL, [Published] DATE NOT NULL,)
Then add a few pieces of data to the table for testing:
Next, let the application connect to the database. Since my previous blog post was written during my company's rest time, my company's computer was installed with VS2010, and my laptop was installed with VS2012, so we have to move the example of the previous blog to VS2012 again. For this example, VS2010 and VS2012 are the same. The directory structure of the sample project in the previous article is as follows:
The example in this article will be continued on the basis of the previous example.
Use NuGet to install the Entity Framework Package in the BookShop. Domain project. For more information, see the previous article in this series.
Add a class named EFDbContext to the Concrete folder of the BookShop. Domain project. The Code is as follows:
public class EFDbContext : DbContext { public DbSet<Book> Books { get; set; } }
The First step to use EF Code First is to create an inherited System. data. entity. dbContext class, which defines an attribute for each table in the database. The attribute name represents the table name in the database. DbSet, as the return type, is a device used to generate CRUD (Create, Read, Update, and Delete) operations and map rows in the database table.
We need to add the database connection string to the web. config configuration file in the BookShop. WebUI project to tell EF how to connect to the database. Configure the connection string based on 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 manual data in the Code to read from the database to test whether the application can connect to the database normally. 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 storage class, we use EF to create an EFDbContext class instance to obtain data in the database. As you can see, we do not need to write the ADO. NET code to connect to and read the database. It is very concise and clear, so we use the Entity Framework. Let's take a look at the running effect:
At this point, we have successfully connected to the database using EF and read data from the database. We can also perform very flexible queries through Linq, just like writing SQL. For example, if you want to query the first 10 records whose prices are less than 100 yuan and display them as low as high as the price, you can write the following in the List Method of BookController under the BookShop. WebUI project:
public ViewResult List() { return View(repository.Books .OrderBy(b => b.Price) .Where(b => b.Price < 100) .Take(10));}
Maybe you will soon have a question about the way EF acquires the database: EF reads data from the entire Books table to the memory, and then returns it to the caller (repository in the code above. books) filter the first 10 pieces of data that the user wants using the Linq statement. If the Books table contains millions of pieces of data, isn't the memory finished? Isn't EF so silly? Does EF intelligently generate SQL text based on the Linq query statement and then query data in the database? Here we will talk about IQueryable and IEnumerable.
IQueryable and IEnumerable
In fact, EF reads data from the entire Books table of the database to the memory for the above-mentioned conditional queries with excessive consideration and sorting conditions, the SQL statement is generated Intelligently Based on the Linq query statement and then executed for query. It is determined by the full encoding. Open the BookRepository class file of the BookShop. Domain project. Note the return type of the Books attribute in this class:
...public IQueryable<Book> Books { get { return context.Books; }}
In the previous blog, we raised a question about using IQueryable as the return type: Why does IQueryable not use IEnumerable as the return type? The answer is: When IQueryable is used, EF will generate an SQL query statement based on the caller's Linq expression, and then execute the query in the database. The queried data is the data the user wants; however, operations such as filtering and sorting by using IEnumerable and Linq expressions are all performed in the memory, that is, EF will first query the data of the entire table from the database and put it in the memory, then, the caller uses the Linq statement to filter, sort, and perform other operations. Is that true? Let's monitor the SQL statements generated by EF in two cases.
Let's take a look at the use of IQueryable. Run the program again, and then use the activity and monitor of SQL Server Management Studio to view the SQL statements executed by our BookShop application. The results are as follows:
The results show that with IQueryable, EF generates corresponding SQL statements based on the Linq expression before executing the query.
Let's slightly modify the code to see how IEnumerable is used. Modify the BookRepository class as follows:
public class BookRepository : IBookRepository { private EFDbContext context = new EFDbContext(); public 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) should also be changed:
public interface IBookRepository { IEnumerable<Book> Books { get; }}
Run the application again, and use the activity and monitor to view the final executed SQL statement, for example:
We can see that after IEnumerable is used, the SQL statement generated by EF does not have any filtering or sorting operations. It selects all the data in the table at a time and has nothing to do with the above written Linq expression.
Although IQueryable can intelligently generate corresponding SQL statements based on the Linq expression, after all, there is a process for analyzing the Linq expression, which is relatively inferior to IEnumerable. So when will we use IEnumerable and IQueryable? I think IEnumerable is suitable for a small amount of data (such as reading application-related system information from a database) and data filtering; when the data volume is large and needs to be filtered (for example, querying by PAGE), it is more appropriate to use IQueryable.
Refer:
Pro ASP. net mvc 4
Http://www.entityframeworktutorial.net/