Mvc+linq+ef Combat (. NET Platform)

Source: Internet
Author: User

the focus of learning software development is hands-on practice, just standing by the River Learning Action Essentials and swimming theory, is never learn to swim, you must try the water. This example practice involves three core knowledge, one is the MVC framework, one is entityframework, and the other is Linq.

First step: Create a new project, creating a MVC application, as shown in:


Step two: inModelLayer Creationedmxfiles and their affiliated classes, which need to be used hereEF. Simply to introduceEFBar,EFis thatEntityFramework, i.e.ORM(objectrelationalmapping) Object Relational database mapping framework, an object-oriented operational framework for manipulating data in data tables based on entity objects. Let's look at how to map database table data with entity objects:

in my SQL Server as shown in the list of pre-built tables, we mainly News table for Operation


in the Models folder Right-click Add New Item, select Data in the list to the left of the dialog box, and then select in the list on the right ADO The Entity Data Model, as shown in:







after a series of actions shown above, we'll see what the system has created for us edmx the graphical display of the file and the file organization structure



in Solution Explorer, in the Models file can see the structure of this file and its sub-files, the role of each file and the principle is no longer explained here, we are interested in their own research.

The third step: code writing, mainly on the Controller for design and coding, there are three main files that need to be written in code, namely HomeController.cs , index.cshtml and the modify.cshtml , respectively, are given as follows:

HomeController.cs the 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>//News list//</summary>/&L T;returns></returns> public ActionResult Index () {//1. Querying the database for news data (performed via 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 Second method: Use LINQ statements to query all news headlines//linq is just the syntax sugar for programmers, and the. NET compiler converts LINQ to Sqo List <Models.news> Li at compile time St = (from D in db.news where d.id! = 0 Select D).            ToList ();            2. Pass the data collection to the View Viewdata["datalist"] = list;        3. Load the View return view ();    } #endregion    #region Perform a delete operation (based on ID) +actionresult Del (int id)///<summary>///(based on ID)//</summa ry>//<param name= "id" > news to be deleted id</param>//<returns></returns> public A Ctionresult Del (int id) {try {//1. Create object to delete news Modeldel = NE                W News () {id = id};                2. Add an object to the EF management container Db.news.Attach (Modeldel);                3. Identify the state of the object wrapper class as Delete state Db.news.Remove (Modeldel); 4. Update to database DB.                SaveChanges ();            5. The update succeeds, so the browser jumps to the list method return Redirecttoaction ("Index", "Home"); } catch (Exception ex) {return Content ("Delete failed! "+ex.            Message); }} #endregion #region display the data to be modified (based on ID) +actionresult Modify (int id) [HttpGet]//&LT ;summary>///Perform modification operations (based on ID)///</summary> <param name= "id" > news id</param> to be modified///<returns></returns> public ActionResult Mo  dify (int id) {try {//Query the database by ID, return to the collection, get the first entity object News n = (from A in db.news where a.id = = ID Select a).                FirstOrDefault (); Generate category drop-down list collection list<selectlistitem> list IEnumerable <SelectListItem> ListItem = (from C in db.ca Tegories select C). ToList (). Select (c=> new SelectListItem {Value =c.id.                ToString (), Text =c.name});                Viewbag.catelist = ListItem;            Pass N to the view display viewbag or ViewData//load view, use view's constructor to pass data to the attribute named model on the view (n); } catch (Exception ex) {return Content ("The modification failed!") "+ Ex.            Message); }} #endregion #region to perform the modification +actionresult Modify (news model) [HttpPost]//<summa Ry>///Perform modification exercisesFor//</summary>//<param name= "model" ></param>//&LT;RETURNS&GT;&LT;/RETURNS&G        T                Public ActionResult Modify (news model) {try {//Add entity objects to the EF object container and get the Pseudo wrapper class object Dbentityentry<news> entry = db.                Entry<news> (model); Sets the state of the wrapper class object to unchanged entry.                state = System.Data.EntityState.Unchanged; Sets the entity attribute entry that needs to be committed. Property (A = A.title).                IsModified = true; Entry. Property (A = A.content).                IsModified = true; Commit to the database to complete modifying the db.                SaveChanges ();            5. The update succeeds, so the browser jumps to the list method return Redirecttoaction ("Index", "Home"); } catch (Exception ex) {return Content ("The modification failed!") "+ Ex.            Message); }} #endregion}}</span>

index.cshtml the code is as follows:

<span style= "FONT-SIZE:18PX;" > @using mvcblog.models @{Layout = null;} <! DOCTYPE html>

modify.cshtml the code is as follows :

<span style= "FONT-SIZE:18PX;" > @model mvcblog. Models. News @{Layout = null;} <! DOCTYPE html>

Fourth step, run the program , what we want to achieve is to News table queries, deletions, and modifications, through the main view Index to display News all the news in the table, and then through the link to the news delete and modify, run the following

    Last mention of this linq linq sqo at compile time lang= "ZH-CN" style= "Font-family:simsun" and this sqo Span lang= "ZH-CN" style= "Font-family:simsun" is defined as more than 50 System.Linq.Enumerable-prepared extension methods in the Ienumerable<t> class. These methods are used to query the collection of its operations, so that we are essentially using the sqo query.

    To summarize the main points of this example, first familiarize yourself with the mvc Frame, this is generally not a problem, its minor will create the Entity Framework, this proficiency is not a problem, in this case I think the most important thing is controller ef Management container medium. Also use the htmlhelper The strongly typed method of the object is directly based on model html control, of course, many parameters of this strongly-typed method are not very skilled, pending further study.

Mvc+linq+ef Combat (. NET platform)

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.