新建實體數據模型
選擇ADO.NET實體數據模型,名稱改為數據庫名
因為使用現有數據庫,所以選擇來自數據庫的EF設計器,只演示所以只選擇一個表,空模型可后期增加表
選擇從數據庫更新模型
新建數據庫連接
選擇EF6.X框架
選擇要查詢數據的表
選擇后的實體數據庫設計視圖
引用異步、EF、數據模型命名空間

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using System.Threading.Tasks; 7 using System.Data.Entity; 8 using WebApplication1.Models; 9 10 namespace WebApplication1.Controllers 11 { 12 public class HomeController : Controller 13 { 14 private NorthwindEntities db = new NorthwindEntities(); 15 public ActionResult Index() 16 { 17 return View(); 18 } 19 20 public ActionResult About() 21 { 22 ViewBag.Message = "Your application description page."; 23 24 return View(); 25 } 26 27 public ActionResult Contact() 28 { 29 ViewBag.Message = "Your contact page."; 30 31 return View(); 32 } 33 //異步加載 34 public async Task<ActionResult> CusAsync() 35 { 36 return View("Customers", await db.Customers.ToListAsync()); 37 } 38 //根據查詢條件 39 public ActionResult Customers() 40 { 41 string id = Request.Params["cusid"]; 42 var cus = from c in db.Customers where c.CustomerID == id select c; 43 return View("Customers", cus); 44 } 45 } 46 }
視圖代碼

1 @model IEnumerable<WebApplication1.Models.Customers> 2 @{ 3 ViewBag.Title = "Customers"; 4 } 5 6 <h2>Customers</h2> 7 <table class="table"> 8 <caption>基本的表格布局</caption> 9 <thead> 10 <tr> 11 <th>CustomerID</th> 12 <th>CompanyName</th> 13 <th>ContactName</th> 14 </tr> 15 </thead> 16 <tbody> 17 @foreach (var item in Model) 18 { 19 <tr> 20 <td>@Html.DisplayFor(modelitem => item.CustomerID)</td> 21 <td>@Html.DisplayFor(modelitem => item.CompanyName)</td> 22 <td>@Html.DisplayFor(modelitem => item.ContactName)</td> 23 </tr> 24 } 25 </tbody> 26 </table>
顯示異步加載效果
根據查詢條件顯示效果