Learning Code First and entityframework in Entity Framework

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

Reprinted: Learn the Code First and entityframework in Entity Framework

I think it's good after reading it. it's suitable for learning materials and I will repost it.

Link: http://www.cnblogs.com/Wayou/archive/2012/09/20/EF_CodeFirst.html

 

This is an article written last week. It was written at the suggestion of the company's haoge. It was originally shared by the department for innovation. I will share it with you here.

 

Recently, in the process of learning MVC, I came into contact with the new design pattern of Code First, which is very novel and convenient. Here I will share some of my understandings.

Concepts to be understood

POCO

The concept of POCO (Plain Old CLR Object) is borrowed from the java POJO, And the meanings of the two are the same. The difference is that the languages used are different. So the explanation of POCO is "Plain Old C # Object ". The internal meaning of POJO refers to objects that have not inherited from any class, nor implemented any interfaces, and are not intruded by other frameworks.

 PO

PO refers to a persistent object (persistant object ). The persistent object must actually correspond to the entity in the database, so it is different from POJO. For example, POJO is created by new and recycled by GC. However, the persistent object is created in the insert database and deleted by the delete database. Basically, the lifecycle of persistent objects is closely related to databases. In addition, persistent objects can only exist in one database Connection. After Connnection is disabled, persistent objects do not exist, and POJO always exists as long as it is not recycled by GC.

 ORM

  ORM (Object/Relational Mapping) Object ing, mainly called the Relational data ing in the database as the Object in the program

Nhib.pdf 

Nhib is an object/Relational Database ing tool for. NET environments. The term object/relational ing (ORM) represents a technology used to map objects represented by the object model to the SQL-based relational model data structure. Therefore, nhibframework and Entity Framework are very similar.

 Entity Framework

The full name of Entity Framework is ADO. NET Entity Framework, which is an ORM (Object/Relational Mapping) Framework developed by Microsoft Based on ADO. NET.


The architecture diagram is as follows:

 

 

 

 

When taking over a new project, we are familiar with and used to design tables in the database after analyzing the requirements, once the table is determined, the changes will not be too large or the structure of the table will almost no longer be changed. The subsequent model compilation and business logic compilation are based on this. This method is called Database First.

Entity Framework 4 released in 2011 has three working methods: Code First, Model First, and Database First. The Code First discussed in this article is a new method.

Code First

To support the design-centric development process, EF4 also supports code-centric development, code-first Development supports a more elegant development process, which allows you:

Develop without using the designer or defining an XML ing file.

· Allows you to write a simple model object POCO (plain old classes) without the need for base classes.

· The database persistence layer does not require any configuration through "conventions are better than configurations"

· You can also overwrite "conventions are better than configurations" and use Smooth APIs to completely customize the persistence layer ing.

Code First is a new development mode based on Entity Framework. It was originally only available in Database First and Model First. Code First, as its name implies, defines your domain model with C #/VB. NET classes, maps these classes to existing databases, or generates new database structures. Code First also supports custom configuration through Data Annotations or fluent APIs.

Two other design methods

Database First is the oldest and most widely used design method. As mentioned above, the design of Database First is highly dependent on the structure of tables in the Database and creates models based on the relationship between tables. If the demand changes or the function changes significantly in the future, the price required to change the database will be high, because the Code previously compiled will no longer apply to new tables, we must refactor to change the logic in the code to adapt to the modified table.

Model Firstj is used to create ADO. NET object objects and their relationships, and then specify the ing to the database. This object is a Model.

Use CodeFirst in MVC

Here I will use a very simple example to demonstrate how Code First works in MVC.

Note: you may need to install Entity Framework 4.1 separately.

ADO. NET Entity Framework 4.1 Installation File: http://www.microsoft.com/download/en/details.aspx? Displaylang = en & id = 8363

 

Let's start with this example. Since Code First is a Code-centric design, we do not care about the specific database structure. We start from analyzing the requirements, that is, the functions we want to implement. Here I just want to implement a page that shows the blog list. Here we do not pay attention to the implementation of CRUD, because these can be automatically generated in MVC. We will see that we did not write SQL statements or use SQL server management studio to design tables in the database, but when we run the program, these required tables have been automatically created, and the data in the database is fully synchronized when we perform the CRUD operation on the page.


Open VS2010 to create an MVC3 project. Note that the environment must be set to. Net Framework 4. Here I name the project MvcBlog.

 

 

Select an empty template. We use ASPX for View engine.

 

 

Because Code First requires EntityFramework support, after the project is created, the system automatically references the EntityFramework assembly for us in the reference. If no, you need to manually reference the assembly.

 

 

(In order to display the complete directory layer structure, I will remove many references in the image and replace them with ellipsis, so don't be surprised when you see this image, my VS is not customized)

First, create a blog class in Model to save the basic information of a blog. It contains a blog ID BlogId, the Title, And the creation date CreateDate.

Right-click the Model folder and choose Add> Class.

 

 

Enter a Blog in Name and click Add.

 

The Code is as follows:

 1 namespace MvcBlog.Models 2  3 { 4  5     public class Blog 6  7     { 8  9         public int BlogId { get; set; }10 11         public string Title { get; set; }12 13        14 15         public DateTime CreateDate { get; set; }16 17     }18 19 }

 

In the same way, we create a new class named BlogEntities. cs, this class is different from the function of the Blog class. We will define it in the Code as inherited from DBContex, in this way, the BlogEntities context class plays an important role in communicating with the database, where you can define the required tables. After the project is run, these tables will be automatically created in the database. Here, we use the defined Blog to define a Dbset. The Code is as follows:

 

1 public class BlogEntities:DbContext2 3     {4 5         public DbSet<Blog> Blogs { get; set; }6 7     }

 

(Note: you must add the using System. Data. Entity reference statement at the top of the file to use DbContext and DbSet)

 

We have prepared the model above and now define the Controller. However, before proceeding to this step, We Need To Ctrl + Shift + B to compile the program so that the system can understand the Blog class and BlogEntities class we have previously defined. Right-click the Controllers folder and select Add-> Controller. The Add Controller dialog box is displayed. Name it HomeController (Controller of MVC. You can also name it as needed, you only need to manually enter the path when opening the webpage). At this moment, the database has not been created and will be automatically created later. There is no data in it. We need to add some data to it, so here we select the template with the CRUD (add, delete, modify, and query) function, then select the following model class as Blog, and the context class as BlogEntities. The system will automatically implement the CRUD operation, you do not need to write it manually.

(Note: You must compile the code before you can find the defined classes in the drop-down menu of this step)

 

 

After you click Add, the generated code is like this:

Namespace MvcBlog. controllers {public class HomeController: Controller {private BlogEntities db = new BlogEntities (); // GET:/Home/public ViewResult Index () {return View (db. blogs. toList ();} // GET:/Home/Details/5 public ViewResult Details (int id) {Blog = db. blogs. find (id); return View (blog);} // GET:/Home/Create public ActionResult Create () {var blog = new Blog (); return View ();} // POST:/Home/Create [HttpPost] public ActionResult Create (Blog blog) {if (ModelState. isValid) {db. blogs. add (blog); db. saveChanges (); return RedirectToAction ("Index");} return View (blog);} // GET:/Home/Edit/5 public ActionResult Edit (int id) {Blog blog = db. blogs. find (id); return View (blog);} // POST:/Home/Edit/5 [HttpPost] public ActionResult Edit (Blog blog) {if (ModelState. isValid) {db. entry (blog ). state = EntityState. modified; db. saveChanges (); return RedirectToAction ("Index");} return View (blog);} // GET:/Home/Delete/5 public ActionResult Delete (int id) {Blog blog = db. blogs. find (id); return View (blog);} // POST:/Home/Delete/5 [HttpPost, ActionName ("Delete")] public ActionResult DeleteConfirmed (int id) {Blog blog = db. blogs. find (id); db. blogs. remove (blog); db. saveChanges (); return RedirectToAction ("Index");} protected override void Dispose (bool disposing) {db. dispose (); base. dispose (disposing );}}}View Code

 

The view is automatically added to the Views folder, so our program can work now, although we don't seem to have done anything. Before running SQL server management studio (or connect to your local database using the server Manager in VS), you can check to see if there is no Blog table in our program in the database. Then we press Ctrl + F5 to run the website.

 

 

The Title field and CreateDate field defined in the Blog are displayed on the page. However, there is no data to display, so only the Title is displayed.

At this time, when we disconnect the database and reconnect, we will find that EF has created a database named MvcBlog. Models. BlogEntities, which contains the Blogs table defined by Dbset. The columns in the table correspond to the fields defined in the Blog class.

 

 

 

After careful observation, you will find that it automatically defines BlogId as the primary key, which is the function of EF convention. If we do not explicitly specify the database connection string and other configuration information, these values follow the conventions in EF, such as the database name MvcBlog. models. blogEntities.

This name is certainly not what we want, and if we install multiple database instances locally, we also want to specify the project to create the data in the desired instance. To override the default conventions, you only need to add the database configuration information in Web. config (Note: it is not the Web. config in the Views folder). The Code is as follows:

<connectionStrings>    <add name="BlogEntities"        connectionString="server=(local)\sqlexpress;database=MvcBlog;integrated security=true;"        providerName="System.Data.SqlClient"/>  </connectionStrings>

 

Note that the above name should be the same as the context class name defined in Models, so that EF can work normally. Replace server with the name of your local database instance. Now we can see that above the previous database, it generated our renamed database.

 

 

 

Run the program again. On the page, click Create New to add several pieces of data.

 

 

 

After adding the data, we will return the changes in the database.

 

 

 

 

The database has saved the data we added on the page.

We have seen the general process of Code First design. Now let's review the previous operations and we will understand how the process is implemented, in particular, code first sets up a data model without database support and then operates on the database.

First, we created the required data model Blog class in Models. The fields contained in the Blog class will be mapped to the corresponding columns in the database table in the future.

Next, we also defined a key BlogEntities context class in the Models folder, which inherits from System. data. dbContext under Entity, which maps our data model to the database and persists the data in the code.

Finally, when adding data on the page, the page returns the form data to the Controller through the Blog type. Here, it processes the Create Action returned by Post, which receives the transmitted data, by calling db. saveChanges () stores data. Here db is an instance of the BlogEntities context class. Through the BlogEntities context class, the RUD operation we perform will be reflected to the database, completing the update process from code to the database.

 

Data Annotations

The above example shows that a blog usually contains classification information, such as logs and essays. Now we will add such a class to save the blog category information. Correspondingly, we should also update our blog class so that it contains a category attribute, in this way, you can specify the category of a blog.

Here we will see how to use Code First to create a foreign key relationship constraint between tables and define other information about the columns in the table, such as the information displayed,

We add a class named Category in the Models folder, which contains a Category ID and a Category name attribute CategoryName. The Code is as follows:

 1 namespace MvcBlog.Models 2  3 { 4  5     public class Category 6  7     { 8  9         public int CategoryId { get; set; }10 11         public string CategoryName { get; set; }12 13     }14 15 }

 

Update Blog class:

 1 namespace MvcBlog.Models 2  3 { 4  5     public class Blog 6  7     { 8  9         public int BlogId { get; set; }10 11         public string Title { get; set; }12 13         public DateTime CreateDate { get; set; }14 15         public int CategoryId { get; set; }16 17     }18 19 }

 

We have added the CategoryId attribute to it, and set it as the foreign key that references the CategoryId in the Category.

There are two methods: Data Annotation and Fluent API to implement this ing to the database. Here we only discuss Data Annotation.

Because CategoryId will become the navigation attribute of the Blog to Category, in addition to adding CategoryId to the Blog, you also need to add an attribute of the Category type. In this way, in the Blog, there will be a declaration from CategoryId in Category.

 1 public class Blog 2  3     { 4  5         public int BlogId { get; set; } 6  7         public string Title { get; set; } 8  9         public DateTime CreateDate { get; set; }10 11         public int CategoryId { get; set; }12 13         public Category Category { get; set; }14 15     }

 

 

Before using Data Annotation to add a foreign key attribute, you must add the System. ComponentModel. DataAnnotations namespace to the Blog class. Then we can add a foreign key attribute on the CategoryId. The changed code is as follows:

public class Blog      {          public int BlogId { get; set; }          public string Title { get; set; }          public DateTime CreateDate { get; set; }          [ForeignKey("CategoryId")]         public int CategoryId { get; set; }          public Category Category { get; set; }      }

 

Update our BlogEntities object at the same time:

1 public class BlogEntities:DbContext2 3     {4 5         public DbSet<Blog> Blogs { get; set; }6 7         public Category Categories { get; set; }8 9     }

 

 

When we run the program, an error is reported,

 

 

Because the database has been created before running the program, but after we make changes to the model, it cannot completely map the changed model to the previous database, so an error will occur. The solution is provided in the error prompt. You can either manually delete the created database or use an instance of DropCreateDatabaseIfModelChanges to initialize the database. Note that in commercial development, the second method should be used with caution because it will automatically delete the previous database and recreate it, however, if you have stored a large amount of information in it, it will be irrecoverable.

Here we do not want to manually delete the model after each modification, so the second method will be very simple, just add the following line to the Application_Start () method of the Global. asax file.

 1 protected void Application_Start() 2  3         { 4  5             Database.SetInitializer(new DropCreateDatabaseIfModelChanges<BlogEntities>()); 6  7             AreaRegistration.RegisterAllAreas(); 8  9  10 11             RegisterGlobalFilters(GlobalFilters.Filters);12 13             RegisterRoutes(RouteTable.Routes);14 15         }

 

In this way, after the model is changed, it will delete the original database and recreate it.

 

Run the program again, and then go to the database. The second table Category has been added, and a foreign key of CategoryId appears in the Blog table, as we want.

 

 

Notes

One is the performance problem. The ObjectContext generated from the database using edm designer stores many things in the CSDL, MSL, and SSDL files, such as some mapping information, when loading a page, you need to load the metadata from the EDM file first, and use Code-first to load data from the Assembly, which should save a lot of time. On the other hand, the CONTEXT object class automatically generated by EF carries a lot of redundant information, which makes the file relatively bloated. It takes no time to read the information in the object class. For more information about performance, see the first article in the reference section.

In addition, there are not many Code First applications. For example, most of them are Database First. Because this is the design method launched by the next-generation EF4.1 of Microsoft, it must have its superiority. Therefore, we can try to design it in future projects.

Postscript

I am also a beginner. I have not studied much deeply. I have learned from many other people's experiences and shared experiences. Coupled with my own innovative understanding, I certainly have something to do with, so I have the right to deepen my understanding, learn with everyone.

Some articles for Reference

1. performance problems found by WCF and Entity framework

Http://www.cnblogs.com/GaryChen/archive/2010/02/06/1664912.html

2. Code-First, Model-First, and Database-First modes in Entity Framework 4

Http://www.cnblogs.com/n-pei/archive/2010/08/12/1797751.html

3. Code-First Development with Entity Framework 4

Http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

4. ADO. NET Entity Framework

Http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework

5. A Code First Example using Entity Framework 4

Http://chris.widdowson.id.au /? P = 746 #

6. Entity Framework At-a-Glance

Http://msdn.microsoft.com/en-us/data/aa937709

7. Three articles about Nadege Deroussen in codeproject

Entity Framework Code First: Let's Try It

Http://www.codeproject.com/Articles/318010/Entity-Framework-Code-First-Let-s-Try-It

EF Code First: Add a Foreign Key relationship

Http://www.codeproject.com/Articles/319366/EF-Code-First-Add-a-Foreign-Key-relationship

EF Data Annotations and Code Fluent

Http://www.codeproject.com/Articles/368164/EF-Data-Annotations-and-Code-Fluent

 

Feel free to repost but keep the link to this page please!

Category: MVC

Related Article

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.