In this article I will explain with an example, how to delete record from Database using Entity Framework Code First Approach in ASP.Net MVC.
Note: If you want to learn about deleting data using Entity Framework Database First Approach, please refer my article Delete Data from Database using Entity Framework Database First Approach.
 
 
Database
Following is the Customers Table generated using Entity Framework Code First Approach.
Note: If you want to learn about inserting data using Entity Framework Code First Approach, please refer my article Insert Data in Database using Entity Framework Code First Approach.
 
Generated Customers Table Schema
Delete Data from Database using Entity Framework Code First Approach
 
Records in Customers Table
Delete Data from Database using Entity Framework Code First Approach
 
 
Namespaces
You will need to import the following namespaces.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
 
 
Model
Following is the Model class Customer.
It is decorated with the Table Data Annotation. It is used to override the default Table name in the Database.
The Model class consists of three properties.
CustomerId
The property CustomerId is decorated with the following two Data Annotation attributes:
Key – It is used to apply the Primary Key constraint to the Column.
DatabaseGenerated – It is used to make the column as an Identity column in the Table i.e. the column that generates its value automatically when record inserted in the table.
 
Name and Country
The properties Name and Country are decorated with the following two Data Annotation attributes:
Required – It sets the column as NOT NULL in the Table which means the column will not accept NULL values.
StringLength – It sets the value of the maximum number of characters allowed in the column. Basically, it is the length of the Field.
[Table("Customers")]
public class Customer
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CustomerId { get; set; }
 
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
 
    [Required]
    [StringLength(50)]
    public string Country { get; set; }
}
 
 
Database Context
Following is the Database Context class, CustomerDBContext. The Connection String is fetched from the Web.Config file using the key.
Note: For more details about Database Context class, please refer my article ASP.Net MVC: Entity Framework Code First Approach example.
 
using System.Data.Entity;
 
public class CustomerDBContext : DbContext
{
    public CustomerDBContext() : base("name=constr")
    {
        // The Database is initialized and created.
        Database.SetInitializer(new CreateDatabaseIfNotExists<CustomerDBContext>());
    }
 
    // A DbSet for each Entity (Table) needs to be added.
    public DbSet<Customer> Customers { get; set; }
 
    // Add a DbSet for each entity type that you want to include in your model.
 
    protected override void OnModelCreating(DbModelBuilder ModelBuilder)
    {
        base.OnModelCreating(ModelBuilder);
    }
}
 
 
Controller
The Controller consists of following two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation for Deleting
Inside this Action method, the Customer Model object is received as parameter.
The CustomerId value of the received Customer Model object is used to reference the Customer record in the CustomerDBContext.
Once the record is referenced, the Customer record is deleted from the Customers table and a message is set in a ViewBag object.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(Customer customer)
    {
        using (CustomerDBContext context = new CustomerDBContext())
        {
            Customer deletedCustomer = (from c in context.Customers
                                        where c.CustomerId == customer.CustomerId
                                        select c).FirstOrDefault();
 
            if (deletedCustomer != null)
            {
                context.Customers.Remove(deletedCustomer);
                context.SaveChanges();
                ViewBag.Message = "Customer record deleted.";
            }
            else
            {
                ViewBag.Message = "Customer not found.";
            }
 
            return View(customer);
        }           
    }
}
 
 
View
Inside the View, in the very first line the Customer Model class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
There is a TextBox created for capturing value for CustomerId using the Html.TextBoxFor method.
There’s also a Submit button at the end of the Form. When the Submit button is clicked, the value of CustomerId is passed to the Action method inside the Controller.
Finally, the value of the ViewBag object is checked for NULL and if it is not NULL then the value of the ViewBag object is displayed using JavaScript Alert MessageBox.
@model EF_CodeFirst_Delete_MVC.Customer
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table border="0" cellpadding="0" cellspacing="0">
            <tr>
                <td style="width: 60px">
                    Id<br />
                    @Html.TextBoxFor(m => m.CustomerId, new { style = "width:50px" })
                </td>
                <td style="width: 200px">
                    <br />
                    <input type="submit" id="btnDelete" value="Delete" />
                </td>
            </tr>
        </table>
    }
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
</body>
</html>
 
 
Screenshot
Delete Data from Database using Entity Framework Code First Approach
 
 
Downloads