MVC learning diary (3) EntityFramework and mvcentityframework
In fact, after learning the creation of the first article and the use of the second article, the basic mvc operations are sufficient. As for the verification of Shenma, it is better to use Jquery and h5 for good-looking applications. So next, in the future, I will talk about some practical things.
As mentioned in previous articles, how can we make your MVC program alive? This requires connecting to the database. I know two methods. One is the well-known ing model, through reflection.
Obtain the structure model of the database, use the Table Builder to reflect the corresponding table, and then use SQL statements to operate on objects. The other is the EntityFramework, a powerful tool in the Microsoft package,
Similarly, EntityFramework is a model for database reflection operations. However, it has been written in a mechanism and can be used quickly. You can use linq statements to restrict the database, very practical (especially for middle-and lower-type projects ),
Next, we will introduce three common creation modes of EF.
The first type of DataFirst is the data priority creation mode, which is the same as that of the word surface. In this way, the EF model must have a database first.
Add an EF model for your MVC project. Right-click your MVC project and give it a name, usually ending with XXXX Content. (Don't ask why, because the rule takes precedence)
After you click "add", the model is automatically selected. The database data on the left is prioritized, and the data on the right is shown below.
After selecting the Connection method, configure the Connection to the database and connect to the database. If there is no Connection, just add New Connection... follow the steps below.
All generated items are in the. edmx file. A. context. cs file is the key to operations.
The class model in the. cs file exactly corresponds to the data tables in the database.
This is the data-first EF model. Let's take a look at how to operate it.
For example, set a PersonController
Method
Var db = new AdventureWorkEntities (); // context class operation object, used to operate the EF model
Public ActionResult Index ()
{
List <Person> persons = from p in db. Person select p;
}
View,
Using namespace. Person class
@ Model namespace. Person class
@ Foreach (Person p in Model)
{
<P>
@ P. name
@ P. age
</P>
}
The general idea of hand playing is that you will be proficient in more exercises.
Next we will describe the second method in EntityFramework. ModelFirst is the model priority principle. As the name suggests, it is to first establish a model, link, and then generate a database. That's right, EF will help you generate a database, you do not need to create a database yourself.
At this time, select the EntityModel on the right. At this time, an EF Model is created first.
Corresponding, an operational Model view appears. You can right-click to add a Model and update or add a database.
The method of adding a Model is also very simple. Taking an object as an operation object can basically be achieved by following steps, which is similar to datafirst. However, the performance is higher than that of datafirst. After all, the priorities and operations are different.
The last codefirst method is later than 3. It is a more efficient method, but it is more troublesome to update. The specific advantages and disadvantages depend on the specific application environment.
This mode parses the operation process of EF.
namespace CodeFirst{ public class Order { public int Id { get; set; } public string Customer { get; set; } public System.DateTime OrderDate { get; set; } public virtual List<OrderDetail> OrderDetails { get; set; } }}
using System;using System.Collections.Generic;namespace CodeFirst{ public partial class OrderDetail { public int Id { get; set; } public string Product { get; set; } public string UnitPrice { get; set; } public int OrderId { get; set; } public virtual Order Order { get; set; } }}
Create object class, basic object class for reflection
With these two classes, Let's define a database context. With them, we can add, delete, modify, and query data. This class must inherit from "System. data. entity. dbContext class to grant it the data operation capability. Therefore, we need to install the EntityFramework package for this application, because so far we have not introduced any content related to the EF framework, and we need to introduce the EF-related assembly. But we have a better choice: NuGet. Online installation through NuGet: Right-click the project and choose "Manage NuGet Packages ..."; Select Online, select EntityFramework, and click Install. If you are not familiar with NuGet, click here to see how to use NuGet to manage the project library. Database context operations:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.Entity;namespace CodeFirst{ public class OrderContext:DbContext { public DbSet<Order> Orders { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } }}
Then we perform the test. In this class, we first created an Order instance and then encoded the query:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace CodeFirst{ class Program { static void Main(string[] args) { using (var ctx = new OrderContext()) { var o = new Order(); o.OrderDate = DateTime.Now; ctx.Orders.Add(o); ctx.SaveChanges(); var query = from order in ctx.Orders select order; foreach (var q in query) { Console.WriteLine("OrderId:{0},OrderDate:{1}", q.Id, q.OrderDate); } Console.Read(); } } }}
If EF Code First is used for the First time, some friends may have doubts. We have not made any database configuration and added a piece of data to be saved through queries. Where is our data? In fact, if you do not configure the database, EF will use ". \ SQLEXPRESS "database instance, if you have not installed". \ SQLEXPRESS "uses LocalDb by default. For details about LocalDb, see SQL Server 2012 Express LocalDB. For example, if my local machine is stored in" C: \ Users \ Kenshin ", you can see that a file named "CodeFirst. orderContext database:
But in most cases, we want to control the database by ourselves. For example, I want it to be saved on my machine ". \ SQL2008 "instance, now we need to go to the configuration file App. configure a database connection string in Config and specify the connection name in the context of our database.
Configuration file:
<?xml version="1.0" encoding="utf-8"?><configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings> <add name="CodeFirstDb" connectionString="Data Source=.\SQL2008;Database=CodeFirstDb;UID=sa;PWD=123;" providerName="System.Data.SqlClient"></add> </connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="v11.0" /> </parameters> </defaultConnectionFactory> </entityFramework></configuration>
OrderContext class. The constructor has an additional connection name parameter:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.Entity;namespace CodeFirst{ public class OrderContext:DbContext { public OrderContext(string connectionName) : base(connectionName) { } public DbSet<Order> Orders { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } }}
When used, enter the name of the configured database connection string:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace CodeFirst{ class Program { static void Main(string[] args) { using (var ctx = new OrderContext("CodeFirstDb")) { var o = new Order(); o.OrderDate = DateTime.Now; ctx.Orders.Add(o); ctx.SaveChanges(); var query = from order in ctx.Orders select order; foreach (var q in query) { Console.WriteLine("OrderId:{0},OrderDate:{1}", q.Id, q.OrderDate); } Console.Read(); } } }}
After the command is executed, it will be found in ". \ SQL2008 "instance has a" CodeFirstDb "Database (note that in addition to the two entity tables we have created, there is also a system table dbo. _ MigrationHistory: it records the definition of the model. In future articles, I will focus on this table ):