(1) 创建模型,在控制器中执行动作方法生成数据显示到视图界面。
[Table("Cinemas")] public class Cinemas { [Key] public int id { get; set; } [Required(ErrorMessage ="名称不能为空!")] [StringLength(50)] public string CName { get; set; } [Required(ErrorMessage ="类型不能为空!")] [StringLength(50)] public string CDescription { get; set; } }
ef映射
public class CinemasMap: EntityTypeConfiguration<Cinemas> { public CinemasMap() { this.HasKey(t => t.id); this.ToTable("Cinemas"); this.Property(t=>t.id).HasColumnName("id"); this.Property(t => t.CName).HasColumnName("CName").HasMaxLength(50); this.Property(t => t.CDescription).HasColumnName("CDescription").HasMaxLength(50); } }
(2) 连接数据库
public class CinemaEntities:DbContext { public CinemaEntities() : base("name=constring") { } public DbSet<Cinemas> Cinemas { get; set; } }
(3) 绑定数据
控制器 CinemaEntities db = new CinemaEntities(); public ActionResult Index() { var list = from s in db.Cinemas select s; return View(list); } 视图页(view) 引用@model IEnumerable<WebApplication1.Models.Cinemas> <table class=" table table-hover"> <tr><td>序号</td><td>名称</td><td>类型</td></tr> @foreach (var item in Model) { <tr><td>@Html.DisplayFor(model => item.id)</td><td>@Html.DisplayFor(model => item.CName)</td><td>@Html.DisplayFor(model => item.CDescription)</td></tr> } </table> 显示数据。
(4) 操作(增删改查)
查询
public ActionResult Index(string searchString) { var list = from s in db.Cinemas select s; if (!string.IsNullOrEmpty(searchString)) { list = list.Where(w => w.CName.Contains(searchString) || w.CDescription.Contains(searchString)); } return View(list); }
删除
public ActionResult Delete(int LID) { logUser model = db.logUser.Find(LID); db.logUser.Remove(model); db.SaveChanges(); return Content("<script type='text/javascript' defer>alert('删除成功');window.location.href='/logUser/Index';</script>"); }
修改
获取对应数据 public ActionResult Edit(int LID) { var log_id = db.logUser.Find(LID); return View(log_id); } 确认修改保存 // POST: logUser/Edit/5 [HttpPost] public ActionResult Edit(logUser model) { try { // TODO: Add update logic here logUser log_id = db.logUser.Find(model.id); log_id.logIp = Request.QueryString["logIp"]; log_id.logTime =Convert.ToDateTime(Request.QueryString["logTime"]); UpdateModel(log_id); db.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } }
增加
public ActionResult Create() { return View(); } 保存 // POST: logUser/Create [HttpPost] public ActionResult Create(logUser model) { try { // TODO: Add insert logic here model.logIp = Request["logIp"]; model.logTime =Convert.ToDateTime(Request["logTime"]); model.userID = 0; db.logUser.Add(model); db.SaveChanges(); return RedirectToAction("Index"); } catch (Exception ex) { return View(ex); } }