ASP. NET MVC4 using EF for database additions and deletions

Source: Internet
Author: User

EF usage Steps: (1) Add EF to project: in model Right click Add New item to find the ADO Entity Data Model, then ... (2) Implementation of database additions and deletions     queries (because the EF entity has been added to the model, so you can do the database operations in the controller) <<controller>>        //Data context object         orderdbentities db = new Orderdbentities ();    & nbsp   Public ActionResult Index () {           //Use SQO (standard query operator), query       &NBS P    //actual return of objects such as IQueryable interface            //iqueryable<models.customer> query = db. Customers.where (d = d.address = = "111");           //This turns out to be abnormal enumerablequery<mode Ls. customer> query = (enumerablequery<models.customer>) db. Customers.where (d = d.address = = "111");           //dbquery supports deferred loading, which is only available when data is used. According to the library                        //DBQUERY&LT;MODELS.CUSTOMER&G T query = db. Customers.where (d = d.address = = "111") as dbquery<models.customer>;           //list<mode Ls. customer> list = query. ToList ();           //can also be            //List<models.cust omer> list = db. Customers.where (d = d.address = = "111"). ToList ();           //In the second way: Using LINQ statements, the syntax is only for programmers, and the. NET compiler translates it into sqo  when compiling assemblies          //iqueryable<models.customer> query = from d in Db. Customers where d.address = = "111" Select d;           //list<models.customer> List = (from D in DB.) Customers where d.address = = "111" Select D). ToList ();            list<models.customer> List = (from d in DB. Customers Select D). ToList ();           //using ViewData to pass data to view            ViewData ["DataList"] = list;    &NBsp       return View ();       } <<view>><body>    < Table border= "1" >          <!--to fetch the data directly @ corresponding to the variable so it's OK (import namespace is also a reason)-->    @foreach (Customer A in viewdata["DataList"] as list<customer>)      {      &NBS P <tr>        <td>@a.Address</td>        <td>@a. customername</td>        <td><a href= "/home/del/@a.customerno" > Delete </a>             <a href= "/home/modify/@a.customerno" > Revision </a>      & nbsp </td>        </tr>   }          </table>& lt;/body>   Delete: <<controller>> public actionresult Del (string id)//This ID is brought over by hyperlinks         {           try            {               //Need a Entity object Parameters                //db. Customers.remove (New Customer () {Customerno = id});               //1, creating the object to delete &N Bsp               Customer Modeldel = new Customer () {Customerno = ID};    &NBS P          //2, add objects to the EF management container                 DB. Customers.attach (Modeldel);               //3, modifying an object's wrapper class object to identify the deletion status     & nbsp           DB. Customers.remove (Modeldel);               //4, update to database         & nbsp       DB. SaveChanges ();               //5, the command tramp redirects to the/home/index method     &NB when the update succeeds Sp          return redirecttoaction ("Index", "Home");           }  &NB Sp         catch (Exception)             {                 //Specify the view for the jump test.cshtml file                r Eturn redirecttoaction ("Test", "Test");               //return Content ("delete failed" + EX . Message);           }       }<<view>> Delete What view, Success failed page is not given    Modify in the view there is definitely another change in the connection, click to jump to the corresponding page, and pass the parameters to the corresponding function <<View>><body>    <table border = "1" >           <!--to fetch the data directly @ corresponding to the variable that is OK (import namespace is also a reason)-->    @ foreach (Customer A in viewdata["DataList"] as list<customer>)      {        &LT;T r>        &Lt;td>@a.address</td>        <td>@a.CustomerName</td>        <td><a href= "/home/del/@a.customerno" > Delete </a>            <a href= "/home/modify/@a.customerno" > Edit </a>        </td>        </tr>   }          </table></body>//calls to the Modify method in the controller, and display the corresponding page as a form <<controller>>  [httpget]//Add this as long as a hyperlink is sent over the call this         Public ActionResult Modify (string id)         {            Customer art = (from D in DB.) Customers where d.address = = "111" Select D). FirstOrDefault ();           //Pass data to view: ViewBag ViewData Using View's constructor       & nbsp     return View (art);       }<<view>>  <body>    @using (Html.BeginForm ("Modify", "Home", FormMethod.Post))      {        <table>             <tr>                &LT;TD colspan = "2" > Edit </td>            </tr>            &LT;TR >                <td> title: @Html. Hiddenfor (A=>a.customerno) </td >                @*<td> @Html. TextBox ("Textname", (object) Model.customerno) </td>*@                <!--using HtmlHelper's strongly-typed approach, Generate text boxes directly from model according to Custoomerno-->                <td> @Html. textboxfor (A = >a.customerno) </td>                <td> @Html. Textboxfor (A =>a . CustomerName) </td>               <td><input type= "Submit" value= "OK to modify"/> @Html. ActionLink ("Back", "index", "Home") </td>             </tr>        </table>   }&LT;/BODY&GT When the user clicks on the modification, the data is sent to the Modify function in the home controller by post to process <<controller>> [httppost]//The form is submitted to call this method         public ActionResult Modify (Customer model)         {        &N Bsp   try            {               //1 to add entity objects to EF Object container, and get the Pseudo wrapper class object                 dbentityentry<customer> entry = db. Entry<customer> (model);               //2, sets the state of the pseudo-wrapper class object to unchanged  & nbsp             entry. State = system.data.entitystate.unchanged;               //3, setting changed properties   &nbsp             entry. Property (A = A.customername). ismodified = true;               //4, submit to database complete changes         &NBSP ;       DB. SaveChanges ();                return redirecttoaction ("Index", "Home");  &NB Sp        }            catch (Exception)             {                return redirecttoaction ("Test", "Test");    &NB Sp      }       }   add: The jump between pages in MVC is through Maprouter code as follows Routes.maproute (  & nbsp             Name: "Default",                URL: "{C Ontroller}/{action}/{id} ",                DEFAULTS:NEW {controller =" Home ", act Ion = "Index", id = UrlpaRameter. Optional} );

ASP. NET MVC4 using EF for database additions and deletions

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.