MVC5 + EF6 + Bootstrap3 (10) Data Query page, mvc5ef6

Source: Internet
Author: User

MVC5 + EF6 + Bootstrap3 (10) Data Query page, mvc5ef6

Source: Slark. NET-blog Park http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-search-page.html

Previous section: MVC5 + EF6 + Bootstrap3 (9) HtmlHelper usage (below)

Download source code: Click here to download

Directory
  • Preface
  • Create Model
  • Create Database context DbContext
  • Create initialization data
  • Create a Controller
  • Create View
  • View results page
  • View Database
  • End
Preface

We have already paved the way for this. Today we use MVC5 + EF6 + Bootstrap3 to formally create a basic query page.

Why does it start from the query page? Hey, because younger brother's. Net career started from the query page. Remember that the first month of formal work was the query of various modules. What are the benefits of querying first? First, query read-only data without writing data. It does not affect the data security of the database itself and is not afraid of the trouble of writing dirty data. In the four operations, add, delete, modify, and query, the query is the least difficult, so you do not need to consider the transaction process and other issues.

The following page is generated at the end of this section:

Create Model

For details about Model, database context, and Entity Framework, this series of tutorials has already been introduced. If you want to review them, please stamp me!

Create a class in the Models folder named Worker. cs. This class is the Model we will use here. The Code is as follows:

 1 namespace SlarkInc.Models 2 { 3     public enum Sex 4     { 5         Male, Female 6     } 7     public class Worker 8     {      9         public int ID { get; set; }10         public string LastName { get; set; }11         public string FirstName { get; set; }12         public Sex Sex { get; set; }13         public double? Rating { get; set; }14     }15 }

For convenience, add the row number. If you want to copy the code, click the small icon in the upper left corner to show the code without the row number. In row 3rd of the Worker class, a Sex Enumeration type is created to ensure that there are only Male and Female values for Sex. In rows 9 to 13, the Worker class defines five attributes using the automatic attribute method. The question mark in front of the Rating attribute indicates that the attribute is nullable and can be null.

Create Database context DbContext

Here we use the Code First method to create a database table. This method is simply to create a Model and then generate a database table based on the Model.

For convenience, the database used here is the LocalDb that comes with Visual Studio.

The database context is the data access layer here, which performs different operations on database tables according to the Model. Therefore, we first create a data access layer folder in the project and name it DAL. Then, create the database access context class corresponding to the Model in the DAL folder and name it CompanyContext. The write code is as follows:

 1 using System.Data.Entity; 2 using SlarkInc.Models; 3 using System.Data.Entity.ModelConfiguration.Conventions; 4  5 namespace SlarkInc.DAL 6 { 7     public class CompanyContext : DbContext 8     { 9         public CompanyContext()  : base("CompanyContext")10         { 11         }12 13         public DbSet<Worker> Workers {get;set;}14 15         protected override void OnModelCreating(DbModelBuilder modelBuilder)16         {17             modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();18         }19     }20 }

Because Entity Framework is used for database access here, System. Data. Entity should be introduced in row 1st. Row 3: Our database context inherits the DbContext base class in EF. Line 3

CompanyContext inherits the constructor of the base class DbContext. Row 13th indicates that our Model Worker corresponds to the Workers dataset in CompanyContext. Lines 15th to 18 define an event

OnModelCreating, this event is triggered when we use the Code First method to create a data table in the database. The function of the Code in Row 3 is to make the names of the created database tables singular, not plural. That is to say, the name of the database table in the future is Worker rather than Workers. This is also the customary naming method for creating database tables.

Then, add the database connection string used by the database context in the Web. config file. As shown in the following code, find the <configuration> element in the Web. config file. Find the <connectionStrings> element in the <configuration> element. Add the following <add> element to the <connectionStrings> element.

<configuration>  <connectionStrings>    <add name="CompanyContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Company;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Company.mdf" providerName="System.Data.SqlClient" />  </connectionStrings><configuration>

In this way, the database context CompanyContext can use this connection string to access the database. Explain the content in the <add> element. Name = "CompanyContext" is the name of the connection string. This parameter must be the same as the parameter of the base ("CompanyContext") function in CompanyContext. cs, so that the string can be read only when the database context is initialized. Data Source = (LocalDb) \ v11.0 indicates the type and version of the database used. Catalog = Company is the name of the database. Integrated Security = SSPI is the verification method. AttachDBFilename = | DataDirectory | \ Company. mdf indicates that the database file exists ~ \ App_Data \ Company. mdf. ProviderName = "System. Data. SqlClient" indicates the Database Connector we want to use here, or the database driver.

Then we need to declare the database context in Web. config. Find the <entityFramework> element in <configuration>. Find the <contexts> element in the <entityFramework> element. Write the following <context> element to the <contexts> element.

<entityFramework>    <contexts>      <context type="SlarkInc.DAL.CompanyContext, SlarkInc">      </context>    </contexts></entityFramework>

Type = "SlarkInc. DAL. CompanyContext, SlarkInc". SlarkInc. DAL. CompanyContext indicates the NameSpace and Class Name of the CompanyContext. The SlarkInc following the comma indicates that the CompanyContext is in SlarkInc. dll.

In this way, CompanyContext is added to the context of the Entity Framework.

Create initialization data

To facilitate the test, we need to add some data to the database after it is created. Therefore, we create a data initialization class to do this. Create a class in the DAL folder named CompanyInitializer. cs. Write the following code:

 1 using System.Collections.Generic; 2 using SlarkInc.Models; 3  4 namespace SlarkInc.DAL 5 { 6     public class CompanyInitializer : System.Data.Entity.DropCreateDatabaseAlways<CompanyContext> 7     { 8         protected override void Seed(CompanyContext context) 9         {10             var students = new List<Worker>11             {12                 new Worker{FirstName="Andy",LastName="George",Sex = Sex.Male},13                 new Worker{FirstName="Laura",LastName="Smith",Sex = Sex.Female},14                 new Worker{FirstName="Jason",LastName="Black",Sex = Sex.Male},15                 new Worker{FirstName="Linda",LastName="Queen",Sex = Sex.Female},16                 new Worker{FirstName="James",LastName="Brown", Sex = Sex.Male}17             };18             students.ForEach(s => context.Workers.Add(s));19             context.SaveChanges();20         }21     }22 }

Row 3: Our data initialization class inherits a generic class named DropCreateDatabaseAlways. This class functions like its name. Every time the program runs, it will delete and recreate the database, this facilitates testing. Rows 8th to 20 are the data initialization functions. The Seed function of the parent class is rewritten and CompanyContext is accepted as the database context for us to operate. Row 3 adds students data to the data set in the database context using the Linq syntax. Row 3 submits the data to the database.

Configure the initialization tool in the Web. config file. Write the following databaseInitializer In the configured <context>.

<contexts>   <context type="SlarkInc.DAL.CompanyContext, SlarkInc">      <databaseInitializer type="SlarkInc.DAL.CompanyInitializer, SlarkInc" />   </context></contexts>

Type = "SlarkInc. DAL. CompanyInitializer, SlarkInc" in SlarkInc. DAL. CompanyInitializer indicates the NameSpace and Class Name of the CompanyInitializer. The SlarkInc following the comma indicates that the CompanyInitializer is in SlarkInc. dll.

In this way, the initialization is complete.

Create a Controller

If you are not familiar with the Controller, please stamp me!

Create a Controller in the Controllers folder and select "MVC 5 Controller-null" and name it CompanyController. cs. The write code is as follows:

 1 using System.Linq; 2 using System.Web.Mvc; 3 using SlarkInc.DAL; 4  5 namespace SlarkInc.Controllers 6 { 7     public class CompanyController : Controller 8     { 9         private CompanyContext db = new CompanyContext();10         public ViewResult Index()11         {12             return View(db.Workers.ToList());13         }14     }15 }

To use the Model and database context created earlier, introduce the DAL namespace in row 3rd and initialize CompanyContext in row 9th. If the return type of Index Action is ViewResult created in Row 3 is ViewResult, a View page is returned for the user request. Then, all the data is transmitted to the View in Row 3. The ToList method of Row 3 Outputs Data in the form of List.

Create View

To create a View corresponding to the Index Action of CompanyController, first create the Company folder under the Views folder. Create an empty view under the Company folder and select the layout page. Name it Index. cshtml. Write the following code:

 1 @model IEnumerable<SlarkInc.Models.Worker> 2 <table class="table"> 3     <tr> 4         <th>@Html.DisplayNameFor(model => model.FirstName)</th> 5         <th>@Html.DisplayNameFor(model => model.LastName)</th> 6         <th>@Html.DisplayNameFor(model => model.Sex)</th> 7         <th>@Html.DisplayNameFor(model => model.Rating)</th> 8     </tr> 9     @foreach (var item in Model)10     {11         <tr>12             <td>13                 @Html.DisplayFor(modelItem => item.FirstName)14             </td>15             <td>16                 @Html.DisplayFor(modelItem => item.LastName)17             </td>18             <td>19                 @Html.DisplayFor(modelItem => item.Sex)20             </td>21             <td>22                 @Html.DisplayFor(modelItem => item.Rating)23             </td>24         </tr>25     }26 </table>

Row 1st indicates that the Model used for this page is the Worker class we created. The following code creates a table to display data sent from the Controller. 4-7 rows pass

DisplayNameFor obtains the attribute name of the Model and displays it as the column header. Row 9-25 displays data through the DisplayFor function.

View results page

Select view in the browser. You can see the following results.

 

The header and tail of the page are applied ~ /Views/Shared/_ Layout. cshtml default Layout. The middle part is the table generated in the Index. cshtml file. The four columns are the four data columns except the id in the Model Worker. The five rows in the table are ~ Data initialized in/DAL/CompanyInitializer. cs.

Right-click any data in the table on the page and select Check elements, as shown in.

In this way, the css style of the corresponding element is displayed on the right side of the F12 developer tool window.

Since <table class = "table"> is set in Index. cshtml, the Bootstrap table style is applied to all elements of this table, as shown below.

View Database

Click Show All files in Solution Explorer to display all files. A database file of CompanyContext. mdf is displayed under App_Data, as shown in.

Double-click the file to display the server resource manager window, as shown in:

We can see two database connections. Don't worry. The first is the connection generated after we run the program, and the second is the connection generated by double-clicking the mdf file. The two connections have the same effect. Double-click the Worker table in the "table" folder of the second connection. You can view the table generated using the EF Code First method. Shown as follows:

The table structure is in the upper-left corner, other table attributes are in the upper-right corner, and SQL statements used to generate the table are in the lower-right corner.

In the server resource manager, right-click the Worker table and select "show table data" to display all the data shown as shown on the page. Is it the same as that displayed on the page?

End

In this section, MVC5 + EF6 + Bootstrap3 is used to create the first official data query page. We will add keyword query, paging, sorting, and other functions to this page. To implement these functions, we will introduce more EF functions and the usage of Linq. Coming soon.

Just like it!

Previous section: MVC5 + EF6 + Bootstrap3 (9) HtmlHelper usage (below)

Author:Slark. NET

Source: http://www.cnblogs.com/slark/

The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable. If you have any questions or suggestions, please give me some further information. Thank you very much.

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.