Trong bài viết này chúng ta sẽ cùng nhau tạo một ứng dụng quản lý sách với chức năng CRUD bằng ASP.NET MVC và áp dụng Entity Framework Code First.
Trước tiên chúng ta cần tạo một project MVC bằng Visual Studio. Ở đây hiện tại mình đang sử dụng Visual Studio 2013
Để làm việc được với Code First thì trước tiên chúng ta phải tiến hành cài đặt Entity Framework vào Project bằng cách như sau:
Chọn menu TOOLS -> Nuget Package Manager -> Package Manager Console. Trong màn hình Package Manager Console chúng ta nhập vào dòng lệnh như sau và nhấn Enter để tiến hành cài đặt:
“Install-Package EntityFramework”
Models:
Trong folder Models chúng ta tạo một class đặt tên là Book chi tiết của class như sau:
- namespace CodeFirstExample.Models
- {
- public class Book
- {
- public int Id { get; set; }
- public string Title { get; set; }
- public string Author { get; set; }
- }
- }
Vẫn ở trong folder Models chúng ta tạo tiếp một class tên là BookContext
- namespace CodeFirstExample.Models
- {
- public class BookContext : DbContext
- {
- public BookContext()
- :base(“name=BookContext”)
- {
- }
- public DbSet<Book> Books { get; set; }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- // khai báo Id sẽ là khóa chính
- modelBuilder.Entity<Book>().HasKey(b => b.Id);
- // khai báo Id sẽ tự động tăng
- modelBuilder.Entity<Book>().Property(b => b.Id)
- .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
- base.OnModelCreating(modelBuilder);
- }
- }
- }
Để Code First có thể làm việc được với SQL Server thì ở đây ta phải khai báo chuỗi Connection String như sau ở bên trong file WebConfig.
- <connectionStrings>
- <add name=“BookContext” connectionString=“Data Source=(localdb)\v11.0;Initial Catalog=CodeFirstExample;Integrated Security=True” providerName=“System.Data.SqlClient” />
- </connectionStrings>
Controller:
Trong folder Controllers chúng ta tạo class có tên là BooksController bằng cách chuột phải lên folder Controllers chọn Add -> Controller:
Lúc này visual studio sẽ tự động sinh ra code để giúp bạn dễ dàng thực hiện cá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()
- {
- return View(db.Books.ToList());
- }
- // GET: Books/Details/5
- public ActionResult Details(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Book book = db.Books.Find(id);
- if (book == null)
- {
- return HttpNotFound();
- }
- return View(book);
- }
- // GET: Books/Create
- public ActionResult Create()
- {
- return View();
- }
- // POST: Books/Create
- // To protect from overposting attacks, please enable the specific properties you want to bind to, for
- // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create([Bind(Include = “Id,Title,Author”)] Book book)
- {
- if (ModelState.IsValid)
- {
- db.Books.Add(book);
- db.SaveChanges();
- return RedirectToAction(“Index”);
- }
- return View(book);
- }
- // GET: Books/Edit/5
- public ActionResult Edit(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Book book = db.Books.Find(id);
- if (book == null)
- {
- return HttpNotFound();
- }
- return View(book);
- }
- // POST: Books/Edit/5
- // To protect from overposting attacks, please enable the specific properties you want to bind to, for
- // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Edit([Bind(Include = “Id,Title,Author”)] Book book)
- {
- if (ModelState.IsValid)
- {
- db.Entry(book).State = EntityState.Modified;
- db.SaveChanges();
- return RedirectToAction(“Index”);
- }
- return View(book);
- }
- // GET: Books/Delete/5
- public ActionResult Delete(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Book book = db.Books.Find(id);
- if (book == null)
- {
- return HttpNotFound();
- }
- return View(book);
- }
- // POST: Books/Delete/5
- [HttpPost, ActionName(“Delete”)]
- [ValidateAntiForgeryToken]
- public ActionResult DeleteConfirmed(int id)
- {
- Book book = db.Books.Find(id);
- db.Books.Remove(book);
- db.SaveChanges();
- return RedirectToAction(“Index”);
- }
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- db.Dispose();
- }
- base.Dispose(disposing);
- }
- }
- }
Thật tuyệt và bây giờ bạn chỉ việc build lại project rồi nhấn F5 để thưởng thức điều tuyệt vời khi làm việc với Code First.