This example demonstrates how to update data 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 UpdateCustomer retrieves a specific customer from the database and updates the customer information. The data update is performed using LINQ to SQL and the changes are saved with SubmitChanges. If the customer is not found or the update 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 the data update process with LINQ to SQL using MVC 5. You need to update 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 güncelleme işlemi
public ActionResult UpdateCustomer(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üşteri bilgilerini güncelle
customer.CustomerName = "Updated Name";
customer.Email = "[email protected]";
// Değişiklikleri kaydet
dataContext.SubmitChanges();
ViewBag.Message = "Müşteri başarıyla güncellendi.";
}
else
{
ViewBag.Message = "Müşteri bulunamadı.";
}
}
return View();
}
}
}