ASP. NET MVC5 + EF6 getting started tutorial (5) Model and Entity Framework, mvc5ef6

Source: Internet
Author: User
Tags sql server express

ASP. NET MVC5 + EF6 getting started tutorial (5) Model and Entity Framework, mvc5ef6

Source: Slark. NET-blog Park http://www.cnblogs.com/slark/p/mvc-5-ef-6-get-started-model.html

Previous section: ASP. net mvc 5 getting started tutorial (4) View and ViewBag

Next section: ASP. NET MVC5 + EF6 getting started tutorial (6) Use Razor in View

Download source code: Click here to download

1. Create a Model

The Model in MVC is an object used to provide display data for the View.

Here we first create a Model object.

In Solution Explorer, right-click the Models folder and choose add> class. Add a Model class named Employee. cs. The Models folder stores all Models by default.

Add the following code to the Employee. cs file:

namespace SlarkInc.Models{    public class Employee    {        public int Id { get; set; }        public string Name { get; set; }        public int Age { get; set; }    }}

In this way, a Model data Model has three attributes: Id, Name, and Age.

Ii. Generate a database

To persist data, Entity Framework is used here.

Entity Framework (EF) is a database access method developed by. NET. Its biggest feature is that it can access data through object-oriented methods without writing SQL statements.

We use the Code First method of EF to create a database table.

Simply put, the Code First method is the First step to use C # To create an entity class. The second step is to generate the corresponding database for this class.

The first step has been completed. Step 2: Create a database context before generating a database table.

Write the code in the Employee. cs file as follows:

using System.Data.Entity;namespace SlarkInc.Models{    public class Employee    {        public int Id { get; set; }        public string Name { get; set; }        public int Age { get; set; }    }    public class EmployeeDBContext : DbContext    {        public DbSet<Employee> Employees { get; set; }    }}

The yellow mark in the figure is the code added for EF persistence.

The EmployeeDBContext class inherits from the DbContext provided by EF. EmployeeDBContext indicates the database context of the Employee, and is responsible for adding, deleting, modifying, and querying data.

Public DbSet <Employee> Employees {get; set;} maps the C # Employee class to the database's Employee table.

The database we use here is SQL Server Express LocalDB. It is a lightweight free version of SQL Server. The advantage is that VS comes with no additional installation. In this way, the code I uploaded for you can directly create a database without additional installation and configuration. Easy to learn.

Next we will configure the database link to connect to this database. Open web. config from the Solution Explorer root directory. This is an XML configuration file. Find the <connectionStrings>... </connectionStrings> element and write the content as follows.

<connectionStrings>    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-SlarkInc-20141130103639.mdf;Initial Catalog=aspnet-SlarkInc-20141130103639;Integrated Security=True"      providerName="System.Data.SqlClient" />    <add name="EmployeeDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Employees.mdf;Integrated Security=True"  providerName="System.Data.SqlClient" />   </connectionStrings>

In the code above, the newly added database link is marked yellow. There are several points worth noting:

  • Name = "EmployeeDBContext" must be the same name as the created DBContext class. In this way, DBContext can use this database link.

  • AttachDbFilename = | DataDirectory | \ Employees. mdf; specifies the storage location and file name of the database files. In general MVC5 projects, it should be in the App_Data folder. The file name is Employees. mdf.

Next we will create the Controller and View that operate the Model.

In Solution Explorer, right-click the Controllers folder and choose add> controller. In the displayed selection bracket window, select the MVC5 controller that contains the view (using Entity Framework ). Click OK.

Configure the controller in the Add controller dialog box.

  • Controller name: EmployeesController
  • Model class: Employee (SlarkInc. Models)
  • Data context: EmployeeDBContext (SlarkInc. Models)
  • Check all the three check boxes below
  • Click Add

The project automatically adds a Controller and View corresponding to the Model class to add, delete, modify, and query the Model.

In Solution Explorer, right-click Index. cshtml In the Employees folder under the Views folder and select view in the browser. The following result is displayed.

The empty list corresponding to a Model is displayed.

Next we will view the database. As shown in, click the small icon under Solution Explorer to display all files ,. Then, the Employees. mdf file is displayed in the App_Data folder. This is the database file created by EF.

Double-click the Employees. mdf file to display the server resource manager window. As shown on the right. Choose data connection> EmployeeDBContext> table> Employees, and double-click. Then, the dbo. Emplyees database table design window is displayed on the homepage. The previous section displays the table structure, and the next section displays the T-SQL statements used to create the table.

So far, the creation of Model and the generation of database tables by using the CodeFirst method of EF have been completed.

Your messages and recommendations are the motivation of my writing. Thank you.

Previous section: ASP. net mvc 5 getting started tutorial (4) View and ViewBag

Next section: ASP. NET MVC5 + EF6 getting started tutorial (6) Use Razor in View

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.