ASP. net mvc 5 + EF 6 getting started tutorial (5) Model and Entity Framework, mvcentity
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
Download source code: Click here to download
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.
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 object class. The second step is to generate a database table 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.
We will introduce how to connect to the database, create a database table, and add data later.
Your messages and recommendations are the motivation of my writing. Thank you.