Entity Framework 6 Recipes Chinese translation series (21), entityframework

Source: Internet
Author: User

Entity Framework 6 Recipes Chinese translation series (21), entityframework

For the original intention of translation and why I chose Entity Framework 6 Recipes, see the beginning of this series.

4.2. Construct a search query

Searching data is a basic function of almost all applications. It is generally dynamic, because the user may use any of the provided conditions, or one is not used. Therefore, we will discuss some details about how to implement this basic function below.

Problem

You want to use the Entity Framework in ASP. NET MVC4 to build a search page.

 

Solution

Suppose you have the model 4-14. In this solution, we plan to use three basic parts to build a search page:

1. A table used to construct query parameters;

2. A WebGrid used to present results in the Razor view;

3. A Cotroller containing the view logic;

In the database, you have a Customer table that stores the Name, City, and State information of all customers. The data model (Architecture) of the Customer table is shown in Figure 4-14.

 

Figure 4-14 a model containing a Customer entity

After the Customer view model is created, we need to use Razor to write the view. In this view, we use the WebGrid control to display Customer records. See the code list 4-5.

Code list 4-5.Use WebGrid In the MVC Razor View

 1 @model EntityFrameworkRecipe2.ViewModels.CustomerVM 2  3 @{ 4     Layout = null; 5 } 6  7 @{ 8     ViewBag.Title = "Customer"; 9     WebGrid grid = new WebGrid(canPage:false,canSort:false);10     grid.Bind(Model.Customers, 11               autoSortAndPage: false12     ); 13 }14 15 @using (Html.BeginForm())16 {17 <table>18     <tr>19         <td>20             Name21         </td>    22         <td>23             @Html.TextBoxFor(model => model.Name)24         </td>25     </tr>26     <tr>27         <td>28             City29         </td>30         <td>31             @Html.TextBoxFor(model => model.City)32         </td>33     </tr>34     <tr>35         <td>36             State37         </td>38         <td>39             @Html.TextBoxFor(model => model.State)40         </td>41     </tr>42     <tr>            43         <td colspan="2">44             <input type="submit" id="search" title="Search" value="Search" />45         </td>46     </tr>47 </table>48 <div id="searchResults">49         <!-- placeHolder for search results -->50         @grid.GetHtml(51             fillEmptyRows: true,52             alternatingRowStyle: "alternate-row",53             headerStyle: "grid-header",54             footerStyle: "grid-footer",55             columns: new [] {56                 grid.Column("Name"),57                 grid.Column("City"),58                 grid.Column("State")59         })60 </div>61 }

Once the view is compiled, I began to write the Get and Post query functions in the Controller. We plan to put the Customer data obtained from the database into view modle, as shown in code list 4-6.

Code list 4-6.Get data generation Search Page Test

 1  public class CustomerController : Controller 2     { 3         public ActionResult Search() 4         { 5             using (var db = new CustomerEntities()) 6             { 7                 var customer = db.Customers.ToList(); 8                 var data = new CustomerVM() 9                 {10                     Customers = customer11                 };12                 return View(data);13             }14         }15         [HttpPost]16         public ActionResult Search(CustomerVM customerVmValue)17         {18             using (var db = new CustomerEntities())19             {20                 var customerSearchResults = from customerRec in db.Customers21                                              where ((customerVmValue.Name == null) || (customerRec.Name == customerVmValue.Name.Trim()))22                                              && ((customerVmValue.City == null) || (customerRec.City == customerVmValue.City.Trim()))23                                              && ((customerVmValue.State == null) || (customerRec.State == customerVmValue.State.Trim()))24                                              select new25                                              {26                                                  Name = customerRec.Name27                                                  ,28                                                  City = customerRec.City29                                                  ,30                                                  State = customerRec.State31                                              };32                 List<Customer> lstCustomer = new  List<Customer>();33                 foreach (var record in customerSearchResults)34                 {35                     Customer customerValue = new Customer();36                     customerValue.Name = record.Name;37                     customerValue.City = record.City;38                     customerValue.State = record.State;39                     lstCustomer.Add(customerValue);40                 }41                 customerVmValue.Customers = lstCustomer;42                 return View(customerVmValue);43             }44         }45     }

 

In your browser, the page is displayed 4-15:

Figure 4-15 view displayed in the browser

 

Principle

In the first section of the page (see the code list 4-5), we use table to format query fields. There is no fancy technology here. We just provide three query fields: name, City, and State structure. Their values (or none) will be used for the Search Action Method of the Controller after the query button is clicked. Therefore, these parameters will become a consideration for the query.

Next, we use HtmlHelper to display the result set in the WebGrid control. The data source uses the view model. Note that we have created two models, one for retrieving data from the database, the other for collecting query parameters on the view page, and displaying the result set.

We use Linq to entities to query the Customer entity in the data model. The where clause and parameters determine our query filtering. In the view, we map the query parameter Name, City, and State to the text box in HtmlHelper. Map the Name attribute to the file box Name, and so on.

The WebGrid control is used to display the result set. It is bound to the CustomerVM. MERs list and is used to obtain the query result set.

The controller code displayed in code list 4-6 retrieves data from the database, loads the view for the first time, and then clicks the query button to fill the view. We used the local database. mdf file and filled the records in the Customer table.

 

 

4.3. Excessive use of ASP. net url Routing

Problem

You want to use MapRoute to simplify your URLs, and you want to use this route to filter the result set in the Razor view engine.

Solution

Suppose you have 4-16 models. We have modeled products and their directories, and represented products with Entity-type products. In a typical e-commerce website, we need to classify products by directory.Do we need to avoid exposing "/Product/Index? Category = Tents. Although this will make programming easier, it is not conducive to search engine optimization. We need to look at URLs like "/Producs/Tents.

Figure 4-6 A categories containing products and them

We can obtain a search engine-friendly URL through routing. The routing is generally created in the Application_Start () event processing function of Global. asax. Code list 4-7 shows how to add a route for the Product controller.

Code list 4-7.Create a route entry in Global. asax

 1 protected void Application_Start() 2         { 3             AreaRegistration.RegisterAllAreas(); 4  5             WebApiConfig.Register(GlobalConfiguration.Configuration); 6             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 7             RouteTable.Routes.MapRoute("Product", "{controller}/{name}", 8                                 new { controller = "Product", action = "Index" } 9                             );10             RouteConfig.RegisterRoutes(RouteTable.Routes);11             BundleConfig.RegisterBundles(BundleTable.Bundles);12             AuthConfig.RegisterAuth();13         }

In the Index View Shown in code listing 4-8, we use the category name to bind the name parameter of the Inde Action Method to the Product controller, as shown in code listing 4-7. We use the code in code listing 4-9 to obtain the value of the category name parameter and process the result set through the view. Figure 4-17 and Figure 4-18 show the product view pages under the Tents directory and the products under the Cooking Equipment directory respectively.

Code list 4-8.The Index view code that displays the products filtered by directories.

 1 @model IEnumerable<EntityFrameworkRecipe3.ViewModels.ProductVM> 2  3 @{ 4     Layout = null; 5 } 6  7 <!DOCTYPE html> 8  9 

Code list 4-9.Controller code, using the Product data filling model filtered by Category Name

 1 public class ProductController : Controller 2     { 3         // 4         // GET: /Product/ 5  6         public ActionResult Index(string name) 7         { 8             using (var db = new ProductEntities()) 9             {10                 var query = from productRec in db.Products11                             join categoryRec in db.Categories12                             on productRec.CategoryId13                             equals categoryRec.CategoryId14                             where categoryRec.Name == name15                             select new16                             {17                                 Name = productRec.Name18                                 ,19                                 CategoryName = categoryRec.Name20                             };21                 List<ProductVM> lstProduct = new List<ProductVM>();22                 foreach(var record in query)23                 {24                     ProductVM productValue = new ProductVM();25                     productValue.Name = record.Name;26                     productValue.CategoryName = record.CategoryName;27                     lstProduct.Add(productValue);28                 }29                 return View(lstProduct);30             }31         }32 33     }

Figure 4-17 use the path "/Product/Tents" to obtain the Product set of the Tents directory category

Figure 4-18 Use the path "/Product/cooking Equipment" to obtain the Product set of the cooking Equipment directory category

 

Principle

In the Applicate_Start () event handler function of Global. asax, we use the previous "/Product/Index? Name = category "ing routing"/Product/{name }". in Product controller, we use the route key and name in MapRoute to filter the result set and filter the Product through the given directory.

 

Now, Chapter 4 is over. Thank you for reading this article. Next, we will go to Chapter 5.


 

 

Entity Framework exchange QQ group: 458326058. You are welcome to join us.

Thank you for your continued attention, my blog address: http://www.cnblogs.com/VolcanoCloud/

 

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.