Adding and Updating Customers Using Entity Framework with MVC 5

This example includes both adding a new customer and updating an existing customer using MVC 5 and Entity Framework. It provides a sample code that includes the MVC Controller and View.

This example shows how to add and update customers to the database with Entity Framework in a web application created using MVC (Model-View-Controller) architecture.

  1. Customer Model (Musteri.cs):
    We create a class named Musteri. This class contains basic information about the customer: name, surname, address, telephone and e-mail. This information will correspond to columns in the database table.
  2. MVC Controller (MusteriController.cs):
    We create a Controller class called MusteriController. This Controller manages the process of adding and updating customers. There are two action methods in the controller:
  • MusteriEkleGuncelle(int? musteriId): This method is used to add or update customers. If musteriId is specified, the page is shown to update an existing customer. If musteriId is not specified, an empty customer is created to add a new customer.
  • [HttpPost] MusteriAddUpdate(Musteri musteri): This method gets the customer information and adds a new customer or updates the existing customer according to this information. It performs model validation and saves the changes to the database.
  • MusteriList(): Shows a page listing all customers.
  1. MVC View (MusteriEkleGuncelle.cshtml):
    We create a View file named MusteriEkleGuncelle.cshtml. This file is used to enter or update customer information. In View, input fields and form are created. This View is linked to the model from the Controller and uses the validation properties of the model.

This example handles adding and updating customers in the same Controller using MVC 5 and Entity Framework. To manage database operations, you need to create the MyDbContext class and configure your database using the Entity Framework Code First approach. This example can help you understand basic CRUD (Create, Read, Update, Delete) operations.

using System.ComponentModel.DataAnnotations;

public class Musteri
{
    public int MusteriId { get; set; }

    [Required]
    [StringLength(50)]
    public string Ad { get; set; }

    [Required]
    [StringLength(50)]
    public string Soyad { get; set; }

    [StringLength(100)]
    public string Adres { get; set; }

    [StringLength(20)]
    public string Telefon { get; set; }

    [Required]
    [StringLength(100)]
    [EmailAddress]
    public string Email { get; set; }
}
using System.Linq;
using System.Web.Mvc;

public class MusteriController : Controller
{
    private MyDbContext dbContext = new MyDbContext(); // Veritabanı bağlamı

    public ActionResult MusteriEkleGuncelle(int? musteriId)
    {
        Musteri musteri;

        if (musteriId.HasValue)
        {
            // Müşteri güncelleme için sayfasını göster
            musteri = dbContext.Musteriler.Find(musteriId);
        }
        else
        {
            // Yeni müşteri eklemek için boş bir müşteri oluştur
            musteri = new Musteri();
        }

        return View("MusteriEkleGuncelle", musteri);
    }

    [HttpPost]
    public ActionResult MusteriEkleGuncelle(Musteri musteri)
    {
        if (ModelState.IsValid)
        {
            if (musteri.MusteriId == 0)
            {
                // Yeni müşteri ekleniyor
                dbContext.Musteriler.Add(musteri);
            }
            else
            {
                // Müşteri güncelleniyor
                var existingMusteri = dbContext.Musteriler.Find(musteri.MusteriId);
                if (existingMusteri != null)
                {
                    existingMusteri.Ad = musteri.Ad;
                    existingMusteri.Soyad = musteri.Soyad;
                    existingMusteri.Adres = musteri.Adres;
                    existingMusteri.Telefon = musteri.Telefon;
                    existingMusteri.Email = musteri.Email;
                }
            }

            dbContext.SaveChanges();
            return RedirectToAction("MusteriListesi");
        }

        return View("MusteriEkleGuncelle", musteri);
    }

    public ActionResult MusteriListesi()
    {
        var musteriler = dbContext.Musteriler.ToList();
        return View("MusteriListesi", musteriler);
    }
}

 

@model YourNamespace.Musteri

@using (Html.BeginForm("MusteriEkleGuncelle", "Musteri", FormMethod.Post))
{
    @Html.HiddenFor(model => model.MusteriId)

    <div class="form-group">
        @Html.LabelFor(model => model.Ad)
        @Html.TextBoxFor(model => model.Ad, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Ad)
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Soyad)
        @Html.TextBoxFor(model => model.Soyad, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Soyad)
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Adres)
        @Html.TextBoxFor(model => model.Adres, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Telefon)
        @Html.TextBoxFor(model => model.Telefon, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Email)
        @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Email)
    </div>

    <button type="submit" class="btn btn-primary">Kaydet</button>
}