Linq To Sql (Insert)

This example demonstrates inserting data with LINQ to SQL using ASP.NET MVC 5. It adds a new customer to a database table named Customer. The operation is performed in an MVC Controller and the results are displayed with a ViewBag.

This example demonstrates adding data using LINQ to SQL in an ASP.NET MVC 5 web application. The first step is to create a model class named Customer. This class represents the columns in the database table and uses LINQ to SQL features. Next, a Controller class is created (CustomerController) and the database connection is specified.

An action called AddCustomer creates a new customer and adds it to the database. The DataContext and Table classes are used to add data using LINQ to SQL. The information of the added customer is transferred to the view using ViewBag.

Finally, a view is created (AddCustomer.cshtml), this view shows the result of the transaction. The user can add a button or other interface element to trigger this transaction.

This example provides a basic understanding of LINQ to SQL using MVC 5 and a starting point for adding data. You need to update the database connection string and data structure to suit your 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.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 ekleme işlemi
        public ActionResult AddCustomer()
        {
            using (DataContext dataContext = new DataContext(connectionString))
            {
                Table<Customer> customers = dataContext.GetTable<Customer>();

                // Yeni bir müşteri oluştur
                Customer newCustomer = new Customer
                {
                    CustomerName = "John Doe",
                    Email = "[email protected]"
                };

                // Müşteriyi veritabanına ekleyin
                customers.InsertOnSubmit(newCustomer);
                dataContext.SubmitChanges();

                ViewBag.Message = "Müşteri başarıyla eklendi. Müşteri ID: " + newCustomer.CustomerID;
            }

            return View();
        }
    }
}