新建实体数据模型
选择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 }