To perform CRUD operations in ASP.NET MVC using Entity Framework, you’ll need to follow these general steps:
- Set up the ASP.NET MVC project and add Entity Framework.
- Create a model class representing the table in the database.
- Create a database context class to interact with the database.
- Implement controllers and views for CRUD operations.
Let’s assume we want to create a simple “Product” table with fields “Id,” “Name,” “Price,” and “Description.” We’ll perform CRUD operations on this table.
Step 1: Set up the ASP.NET MVC project and add Entity Framework
- Create a new ASP.NET MVC project in Visual Studio.
- Install Entity Framework NuGet package:
- Right-click on the project > Manage NuGet Packages.
- Search for “Entity Framework” and install it.
Step 2: Create the model class
- Create a new folder named “Models” in the project.
- Inside the “Models” folder, create a new class file called “Product.cs” with the following code:
using System.ComponentModel.DataAnnotations;
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public decimal Price { get; set; }
public string Description { get; set; }
}
Step 3: Create the database context class
- Create a new class file called “AppDbContext.cs” in the project.
- Inside the class, inherit from
DbContextclass and add aDbSetfor the “Product” model:
using System.Data.Entity;
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
}Step 4: Implement controllers and views for CRUD operations
- Right-click on the “Controllers” folder in the project, and choose “Add” > “Controller.”
- Select “MVC 5 Controller with views, using Entity Framework.”
- Choose the “Product” model and the “AppDbContext” context you created earlier.
- This will generate a controller with pre-defined actions for CRUD operations (Index, Create, Edit, Delete, Details).
Now, your project is set up with the basic CRUD operations for the “Product” table using Entity Framework in ASP.NET MVC.
Remember that you may need to adjust the code according to your specific use case, but this should give you a general idea of how to perform CRUD operations with Entity Framework in an ASP.NET MVC project.
Here’s the code for the controller with all the CRUD operations:
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
public class ProductsController : Controller
{
private AppDbContext db = new AppDbContext();
// GET: Products
public ActionResult Index()
{
var products = db.Products.ToList();
return View(products);
}
// GET: Products/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// GET: Products/Create
public ActionResult Create()
{
return View();
}
// POST: Products/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Price,Description")] Product product)
{
if (ModelState.IsValid)
{
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
// GET: Products/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// POST: Products/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Price,Description")] Product product)
{
if (ModelState.IsValid)
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
// GET: Products/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Product product = db.Products.Find(id);
db.Products.Remove(product);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}Â
This controller contains actions for listing all products (Index), displaying details (Details), creating a new product (Create), editing an existing product (Edit), and deleting a product (Delete). It also handles form submissions to perform the corresponding CRUD operations on the database. Additionally, it disposes of the database context when it’s no longer needed.
Please note that the [Bind(Include = "Id,Name,Price,Description")] attribute is used to prevent over-posting (mass assignment) of unwanted properties during model binding. It includes only the specified properties in the binding process.
Make sure to update the namespace and class names as per your project’s structure. Also, don’t forget to create views for these actions to complete the implementation. The views will allow users to interact with the CRUD operations visually.
The step-by-step instructions on how to add views for all the actions in the “Products” controller. This will allow users to interact with the CRUD operations visually.
- Open Visual Studio and your ASP.NET MVC project.
- In the Solution Explorer, find the “Controllers” folder and open the “ProductsController.cs” file.
- Add the following code at the top of the file to include the necessary namespaces:
using System.Data.Entity; using System.Linq; using System.Net; using System.Web.Mvc;
- Right-click on the “Index” action method in the controller and select “Add View.”
- In the “Add View” dialog, set the following options:
- View name: Index
- Template: List
- Model class: Product (fully qualified class name: YourProjectName.Models.Product)
- Uncheck “Use a layout page” (for simplicity)
- Click the “Add” button to add the “Index” view.
- Repeat steps 4-6 for the “Details” action method:
- View name: Details
- Template: Details
- Model class: Product
- Repeat steps 4-6 for the “Create” action method:
- View name: Create
- Template: Create
- Model class: Product
- Repeat steps 4-6 for the “Edit” action method:
- View name: Edit
- Template: Edit
- Model class: Product
- Repeat steps 4-6 for the “Delete” action method:
- View name: Delete
- Template: Delete
- Model class: Product
After following these steps, Visual Studio will generate the views for all the CRUD actions with the necessary HTML and form elements. You can further customize these views as per your project’s requirements. The generated views will be stored in the “Views” folder, organized in a “Products” subfolder.
Once the views are generated, users will be able to interact with the CRUD operations through these views. For example, the “Index” view will display a list of products, the “Details” view will show detailed information about a product, the “Create” view will allow users to add new products, the “Edit” view will allow users to modify existing products, and the “Delete” view will confirm the deletion of a product.
Note: If there is any confusion, and found any error in the code. Kindly comment or post your question in ask section.
Thank you.