Sử dụng entity framework code first trong ASP NET MVC

9 193 0
Sử dụng entity framework code first trong ASP NET MVC

Đang tải... (xem toàn văn)

Thông tin tài liệu

Sử dụng Entity Framework Code First ASP.NET MVC Trong viết tạo ứng dụng quản lý sách với chức CRUD ASP.NET MVC áp dụng Entity Framework Code First Trước tiên cần tạo project MVC Visual Studio Ở sử dụng Visual Studio 2013 Để làm việc với Code First trước tiên phải tiến hành cài đặt Entity Framework vào Project cách sau: Chọn menu TOOLS -> Nuget Package Manager -> Package Manager Console Trong hình Package Manager Console nhập vào dòng lệnh sau nhấn Enter để tiến hành cài đặt: “Install-Package EntityFramework” Models: Trong folder Models tạo class đặt tên Book chi tiết class sau: namespace CodeFirstExample.Models { public class Book { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } } } Vẫn folder Models tạo tiếp class tên BookContext namespace CodeFirstExample.Models { public class BookContext : DbContext { public BookContext() :base("name=BookContext") { } 10 public DbSet Books { get; set; } 11 12 protected override void OnModelCreating(DbModelBuilder modelBuilder) 13 { 14 // khai báo Id khóa 15 modelBuilder.Entity().HasKey(b => b.Id); 16 17 // khai báo Id tự động tăng 18 modelBuilder.Entity().Property(b => b.Id) 19 HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); 20 base.OnModelCreating(modelBuilder); 21 } 22 } 23 } Để Code First làm việc với SQL Server ta phải khai báo chuỗi Connection String sau bên file WebConfig Controller: Trong folder Controllers tạo class có tên BooksController cách chuột phải lên folder Controllers chọn Add -> Controller: Lúc visual studio tự động sinh code để giúp bạn dễ dàng thực thao tác CRUD (Create – Read – Update – Delete) namespace CodeFirstExample.Controllers { public class BooksController : Controller { private BookContext db = new BookContext(); // GET: Books public ActionResult Index() { 10 11 return View(db.Books.ToList()); } 12 13 // GET: Books/Details/5 14 public ActionResult Details(int? id) 15 { 16 if (id == null) 17 { 18 return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 19 } 20 Book book = db.Books.Find(id); 21 if (book == null) 22 { 23 return HttpNotFound(); 24 } 25 return View(book); 26 } 27 28 // GET: Books/Create 29 public ActionResult Create() 30 { 31 32 return View(); } 33 34 // POST: Books/Create 35 // To protect from overposting attacks, please enable the specific properties you want to bind to, for 36 // more details see http://go.microsoft.com/fwlink/?LinkId=317598 37 [HttpPost] 38 [ValidateAntiForgeryToken] 39 40 public ActionResult Create([Bind(Include = "Id,Title,Author")] Book book) { 41 if (ModelState.IsValid) 42 { 43 db.Books.Add(book); 44 db.SaveChanges(); 45 return RedirectToAction("Index"); 46 } 47 48 49 return View(book); } 50 51 // GET: Books/Edit/5 52 public ActionResult Edit(int? id) 53 { 54 if (id == null) 55 { 56 57 return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } 58 Book book = db.Books.Find(id); 59 if (book == null) 60 { 61 return HttpNotFound(); 62 } 63 return View(book); 64 } 65 66 // POST: Books/Edit/5 67 // To protect from overposting attacks, please enable the specific properties you want to bind to, for 68 // more details see http://go.microsoft.com/fwlink/?LinkId=317598 69 [HttpPost] 70 [ValidateAntiForgeryToken] 71 book) 72 public ActionResult Edit([Bind(Include = "Id,Title,Author")] Book { 73 if (ModelState.IsValid) 74 { 75 db.Entry(book).State = EntityState.Modified; 76 db.SaveChanges(); 77 return RedirectToAction("Index"); 78 } 79 return View(book); 80 } 81 82 // GET: Books/Delete/5 83 public ActionResult Delete(int? id) 84 { 85 if (id == null) 86 { 87 return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 88 } 89 Book book = db.Books.Find(id); 90 if (book == null) 91 { 92 return HttpNotFound(); 93 } 94 return View(book); 95 } 96 97 // POST: Books/Delete/5 98 [HttpPost, ActionName("Delete")] 99 [ValidateAntiForgeryToken] 100 public ActionResult DeleteConfirmed(int id) 101 { 102 Book book = db.Books.Find(id); 103 db.Books.Remove(book); 104 db.SaveChanges(); 105 return RedirectToAction("Index"); 106 } 107 108 protected override void Dispose(bool disposing) 109 { 110 if (disposing) 111 { 112 db.Dispose(); 113 } 114 base.Dispose(disposing); 115 116 } } 117 } Thật tuyệt bạn việc build lại project nhấn F5 để thưởng thức điều tuyệt vời làm việc với Code First Download project đây: https://github.com/khiemnvd/CodeFirstExample ... Manager -> Package Manager Console Trong hình Package Manager Console nhập vào dòng lệnh sau nhấn Enter để tiến hành cài đặt: “Install-Package EntityFramework” Models: Trong folder Models tạo class... lại project nhấn F5 để thưởng thức điều tuyệt vời làm việc với Code First Download project đây: https://github.com/khiemnvd/CodeFirstExample ... Source=(localdb)v11.0;Initial Catalog=CodeFirstExample;Integrated Security=True" providerName="System.Data.SqlClient" /> Controller: Trong folder Controllers tạo class có

Ngày đăng: 03/06/2019, 15:01

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan