A. Create A basic type project.
B. Create the following files under the Model directory:
Student.cs:
Using system;using system.collections.generic;using system.linq;using system.web;using System.componentmodel.dataannotations.schema;namespace mvcsqltest.models{public class Student { public int Id {set; get;} public string Name {set; get;} public int Age {set; get;} public string Class {set; get;} [Notmapped] public string Country { get { return ' China '; } }}
C. Create a controller:
HomeController.cs:
Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;namespace mvcsqltest.controllers{public class Homecontroller:controller { //// GET:/home/ Public ActionResult Index () { return View ();}} }
StudentController.cs:
Using system;using system.collections.generic;using system.data;using system.data.entity;using System.Linq;using System.web;using system.web.mvc;using mvcsqltest.models;using system.transactions;namespace MvcSqlTest.Controllers {public class Studentcontroller:controller {private Mvcsqltestcontext db = new Mvcsqltestcontext (); Public ActionResult Index () {return View (db. Students.tolist ()); Public ActionResult Selectsql (string Name) {Student Student = db. Students.sqlquery ("select * from Students where [email protected]", Name). Single (); Return View ("Details", student); } public ActionResult Deletesql (string Name) {using (TransactionScope ts = new TransactionScope ( ) {String sql = "Delete from Students where name={0}"; Db. Database.executesqlcommand (SQL, Name); Ts. Complete (); } return Redirecttoaction ("Index"); } public ActionResult Create () {return View (); } [HttpPost] public actionresult Create (Student Student) {if (modelstate.isvalid) {db. Students.add (student); Db. SaveChanges (); Return redirecttoaction ("Index"); } return View (student); } protected override void Dispose (bool disposing) {db. Dispose (); Base. Dispose (disposing); } }}
D. Create the appropriate view:
Home/index.cshtml:
@{ viewbag.title = "Index";}
Tip: Create a view under the Student directory with Platform Technology and Entity Framework Technology:create.cshtml,details.cshtml,index.cshtml and generate the corresponding database files.
Once again, modify the index.cshtml:
@model ienumerable<mvcsqltest.models.student>@{viewbag.title = "Index";} E. After the homepage is launched, students are added through student management. Then, test [query] and [delete] functions.The AspNet MVC4 teaching -26:asp.net MVC4 The original ecology SQL Technology Rapid Application Demo