EF的入门使用 (电影管理)

控制器代码:

    public class HomeController : Controller
    {
        private NewDBContext ndc = new NewDBContext();

        public ActionResult index(string search)
        {
            List<Movie> b = ndc.movies.ToList();
            if (string.IsNullOrEmpty(search))
                b.Where(x => x.Title == search).ToList();

            ViewData["Title"] = b.Select(a => new SelectListItem { Value = a.Title, Text = a.Title }).ToList();
            return View(b);
        }
        [HttpPost]
        public string Index(string search)
        {
            return "this post " + search;
        }

        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Movie b)
        {
            if (ModelState.IsValid)
            {
                ndc.movies.Add(b);
                ndc.SaveChanges();
            }
            return RedirectToAction("index");
        }

        public ActionResult Edit(int id)
        {
            Movie m = ndc.movies.Find(id);
            if (m == null)
                return HttpNotFound();
            return View(m);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Movie m)
        {
            if (ModelState.IsValid)
            {
                ndc.Entry(m).State = EntityState.Modified;
                ndc.SaveChanges();
                return RedirectToAction("index");
            }
            return View(m);
        }


        public ActionResult Details(int id)
        {
            Movie m = ndc.movies.Find(id);
            if (m == null) return HttpNotFound();
            return View(m);
        }


        public ActionResult Delete(int id)
        {
            Movie m = ndc.movies.Find(id);
            if (m == null) return HttpNotFound();
            ndc.movies.Remove(m);
            ndc.SaveChanges();
            return RedirectToAction("index");
        }
            

    }
View Code

模型代码

    public class Movie
    {
        public int Id { get; set; }
        [Required]
        [Display(Name = "标题")]
        [StringLength(30,MinimumLength =1)]
        public string Title { get; set; }

        [Required]
        [Display(Name = "时间")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
        public DateTime ReleaseDate { get; set; }

        [Required]
        [Display(Name = "作者")]
        public string Genre { get; set; }
        [Display(Name = "价格")]   
        [Range(1,100)]
        [DataType(DataType.Currency)]     
        public decimal Price { get; set; }
    }
    public class NewDBContext : DbContext
    {
        public DbSet<Movie> movies { get; set; }
    }
View Code

---------------------------------------------

附带代码包:控制器位home

http://pan.baidu.com/s/1mh0T77a

原文地址:https://www.cnblogs.com/0to9/p/5248240.html