Linq To Sql (Delete)

This example demonstrates data deletion with LINQ to SQL using ASP.NET MVC 5. It deletes a specific customer from a model class named Customer from the database. This operation is performed within a Controller action.

This example demonstrates data deletion using LINQ to SQL in an ASP.NET MVC 5 web application. First, a model class named Customer is defined. This class represents the columns in the database table and uses LINQ to SQL features. Next, a Controller class named CustomerController is created and the database connection is specified.

An action named DeleteCustomer retrieves a specific customer from the database and deletes that customer from the database using DeleteOnSubmit. Changes are saved using SubmitChanges. If the customer is not found or the deletion fails, the appropriate messages are passed to the view with ViewBag.

Finally, a view is created and an interface element is added to trigger this operation. This example provides a starting point for understanding and implementing data deletion with LINQ to SQL using MVC 5. You should adjust the database connection string and data structure according to your own application.

using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace YourMvcApplication.Models
{
    [Table(Name = "Customers")]
    public class Customer
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public int CustomerID { get; set; }

        [Column]
        public string CustomerName { get; set; }

        [Column]
        public string Email { get; set; }
    }
}

 

using System;
using System.Linq;
using System.Web.Mvc;
using YourMvcApplication.Models;

namespace YourMvcApplication.Controllers
{
    public class CustomerController : Controller
    {
        // Veritabanı bağlantı dizesi
        private string connectionString = "your_connection_string_here";

        // Müşteri silme işlemi
        public ActionResult DeleteCustomer(int id)
        {
            using (DataContext dataContext = new DataContext(connectionString))
            {
                Table<Customer> customers = dataContext.GetTable<Customer>();

                // Veritabanından belirli bir müşteriyi alın
                Customer customer = customers.SingleOrDefault(c => c.CustomerID == id);

                if (customer != null)
                {
                    // Müşteriyi sil
                    customers.DeleteOnSubmit(customer);
                    dataContext.SubmitChanges();

                    ViewBag.Message = "Müşteri başarıyla silindi.";
                }
                else
                {
                    ViewBag.Message = "Müşteri bulunamadı.";
                }
            }

            return View();
        }
    }
}