MVC + LINQ + EF (. NET platform), mvclinq

Source: Internet
Author: User

MVC + LINQ + EF (. NET platform), mvclinq

The focus of learning software development is hands-on practice. It is just to stand by the river to learn the essentials of action and the theory of swimming. You will never learn to swim. You must try it out. This example mainly involves three core knowledge parts: MVC Framework, EntityFramework, and Linq.

Step 1: Create a project and create an MVC-based application, as shown in:


Step 2: Create an edmx file and its ancillary classes at the Model layer. EF is used here. EF is the EntityFrameWork, that is, the object relational database ing framework of ORM (ObjectRelationalMapping). It operates an object-oriented operation framework of data in a data table based on an object. Next, let's take a look at how to map data in a database table with an object:

Shows several tables created in advance in My SQL Server. We mainly operate on the news table.


In the Models folder, right-click Add new item, select data in the list on the left of the dialog box, and then select ADO. NET Object Data Model in the list on the right, as shown in:







After a series of operations shown above, we will see the graphic display and file organization structure of the edmx file created for us by the system, as shown in



Under the Models file in solution resource manager, you can see the organizational structure of this file and its sub-files. The roles and principles of each file are not described here. If you are interested, you can study it on your own.

Step 3: write the code, mainly to design and code the Controller. The three files that need to write the code are HomeController. cs, Index. cshtml and Modify. cshtml:

The HomeController. cs code is as follows:

<Span style = "font-size: 18px;"> namespace MVCBlog. controllers {public class HomeController: Controller {// <summary> // data context object /// </summary> newssystemEntities db = new newssystemEntities (); # region Query News list + ActionResult Index () /// <summary> /// query the news list /// </summary> /// <returns> </returns> public ActionResult Index () {// 1. query news data in the database (executed through EF) // 1.1 first method: Use SQO (standard query operator) to query all news/db. news. where (d => D. id! = 0); // List <Models. news> list = db. news. Where (d => d. id! = 0 ). toList (); // 1.2 Method 2: Query all news headlines using a linq statement. // Linq is only the syntactic sugar used by programmers ,. the net compiler will convert linq to sqo List <Models. news> list = (from d in db. news where d. id! = 0 select d ). toList (); // 2. pass the data set to ViewData ["datalist"] = list; // 3. load the View return View () ;}# endregion # region: Perform the delete operation (based on id) + ActionResult Del (int id) /// <summary> /// perform the delete operation (based on the id) /// </summary> /// <param name = "id"> id of the news to be deleted </param> /// <returns> </returns> public ActionResult Del (int id) {try {// 1. create the news modelDel = new news () {id = id}; // 2. add the object to the EF management container db. news. attach (modelDel); // 3. set The status of the object packaging class is deleted db. news. remove (modelDel); // 4. update to database db. saveChanges (); // 5. if the update is successful, the browser will jump to the list method return RedirectToAction ("Index", "Home");} catch (Exception ex) {return Content ("deletion failed! "+ Ex. message) ;}# endregion # region displays the data to be modified (based on id) + ActionResult Modify (int id) [HttpGet] /// <summary> /// perform the modification operation (based on the id) /// </summary> /// <param name = "id"> id of the news to be modified </param> /// <returns> </returns> public ActionResult Modify (int id) {try {// query the database by id. Return the collection and obtain the first object news n = (from a in db. news where. id = id select ). firstOrDefault (); // generate the List set of category drop-down lists <SelectListItem> list IEnumerable <Sel EctListItem> listitem = (from c in db. categories select c ). toList (). select (c => new SelectListItem {Value = c. id. toString (), Text = c. name}); ViewBag. cateList = listitem; // pass n to the view to display viewbag or viewdata // load the view, use the view constructor to pass data to the return View (n);} catch (Exception ex) {return Content ("modification failed! "+ Ex. message) ;}# endregion # region executes the modification operation + ActionResult Modify (news model) [HttpPost] /// <summary> /// execute the modification operation // </summary> /// <param name = "model"> </param> /// <returns> </returns> public ActionResult Modify (news model) {try {// Add the object to the EF object container and obtain the pseudo-packaging Class Object DbEntityEntry <news> entry = db. entry <news> (model); // set the state of the packaging class object to unchanged entry. state = System. data. entityState. unchanged; // set object attributes to be submitted Entry. property (a =>. title ). isModified = true; entry. property (a =>. content ). isModified = true; // submit it to the database to complete the modification. saveChanges (); // 5. if the update is successful, the browser will jump to the list method return RedirectToAction ("Index", "Home");} catch (Exception ex) {return Content ("modification failed! "+ Ex. Message) ;}}# endregion }}</span>

The Index. cshtml code is as follows:

<Span style = "font-size: 18px;"> @ using MVCBlog. Models @ {Layout = null ;}<! DOCTYPE html> 

The code for Modify. cshtml is as follows:

<Span style = "font-size: 18px;"> @ model MVCBlog. Models. news @ {Layout = null ;}<! DOCTYPE html> 

Step 4: run the program to query, delete, and modify the news table. The main view Index is used to display all the news in the news table, then, click the link to delete and modify the news, and run the following:

 

Finally, I would like to mention this Linq, which may be confusing to friends I have never heard. The so-called Linq is language integration query. It is an innovative feature introduced in Visual Studio 2008 and. NET Framework 3.5. It builds a bridge between the object field and the data field. Linq is just a syntactic sugar for programmers ,. the net compiler will convert linq to SQO during compilation, and this SQO is defined in System. linq. more than 50 extension methods in the Enumerable class are prepared for IEnumerable <T>. These methods are used to filter the set in which they are operated. Therefore, SQO is essentially used for query.

To sum up the key points of this instance, you must first be familiar with the MVC framework. This is generally no problem. Second, you must create an entity framework. This is no problem if you are skilled, in this example, I think the core thing is to write the Controller, which requires a lot of knowledge, such as how to create an object and add the operation object to the EF management container. In addition, the strong type method of HtmlHelper object is also used in the distribution view to generate html controls directly based on the model attributes. Of course, many parameters of this strong type method are not very skilled and need further study.

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.