Entity Framework

Günümüzde klasik AdoNet kodlarını çok fazla kullandığımızı söyleyemeyiz.

AdoNet yerine bu işlemleri bizim için oldukça kolaylaştıran ORM teknolojileri mevcuttur.

ORM: Object Relational Mapping (Nesne-İlişkisel Eşleme) bu sistemde veritabanı nesneleri ile classlarımızı birbiriyle ilişkilendirip bunlar üzerinde rahatlıkla nesnel veri tabanı programlama yapılır.

1.Projeye eklemek için Project>ManageNuGetPackages>Browse> Entity Framework aratılarak yüklenir

Öncelikle tablomuzdaki alanların karşılıklarını tutan Product classını oluşturduk

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFrameworkDemo
{
    public class Product
    {
        //Products tablomuzun karşılığını Product class'ında aynen oluşturalım
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal UnitPrice { get; set; }
        public int StockAmount { get; set; }
    }
}

Sonrasında tablolarımızın karşılığı tutan Context class’ını oluşturduk.

ETradeContext.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFrameworkDemo
{
    class ETradeContext :DbContext
    {
        public DbSet<Product> Products { get; set; }
        //Benim bir Product'um var onu entity seti olarak (tablo gibi) Products ismiyle kullanacağım 
    }
}

Projemizdeki App.config dosyasına giderek bağlantı adresimizi configsection’un altına ekledik (name, context name’mimizle aynı olmalı)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework"
          type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
          requirePermission="false"/>
    </configSections>
  <connectionStrings>
    <add name="ETradeContext" connectionString="server=(localdb)\MSSQLLocalDB;initial catalog=ETrade;integrated security=true" providerName="System.Data.SqlClient"/>
  </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
    </startup>
    <entityFramework>
        <providers>
            <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
        </providers>
    </entityFramework>
</configuration>

Sonrasında CRUD operasyonlarımızı çağıracağımız ProductDal (Product Data Access Layer) classımızı oluşturduk

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFrameworkDemo
{
    public class ProductDal
    {
        //SELECT
        public List<Product> GetAll()
        {
            //SELECT (Entity)
            //EtradeContext pahallı bir nesne bellekte çok yer kaplıyor. Biz using kullanmadan ETradeContext context = new ETradeContext(); şeklinde de çağırabilirdik
            //using kullanarak nesnemizle işimiz bittiği anda Garbage Collector'u beklemeden, nesneyi zorla bellekten atıyoruz(dispose ediyoruz)            
            using (ETradeContext context = new ETradeContext())
            {
                return context.Products.ToList();   //Method çalıştığı zaman Db'den ürünleri çekip listeye çevirecek ve döndürecek
            }
        }

        //INSERT
        public void Add(Product product)
        {
            using (ETradeContext context = new ETradeContext())
            {
                context.Products.Add(product);
                //var entity = context.Entry(product);  //Bu şekilde de yapabiliriz
                //entity.State = EntityState.Added;
                context.SaveChanges();
            }
        }

        //UPDATE
        public void Update(Product product)
        {
            using (ETradeContext context = new ETradeContext())
            {
                var entity = context.Entry(product);    //Gönderdiğimiz product'ı veritabanındaki product'a eşitle
                entity.State = EntityState.Modified;
                context.SaveChanges();
            }
        }
        
        //DELETE
        public void Delete(Product product)
        {
            using (ETradeContext context = new ETradeContext())
            {
                var entity = context.Entry(product);    //Gönderdiğimiz product'ı veritabanındaki product'a eşitle
                entity.State = EntityState.Deleted;
                context.SaveChanges();
            }
        }
    }
}

WinForm uygulamasına giderek tasarımlarımızı yaptık ve ProductDal classımızdan ilgili komutları çağırdık

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EntityFrameworkDemo
{
    public partial class Form1 : Form
    {
        /*
         * Günümüzde klasik AdoNet kodlarını çok fazla kullandığımızı söyleyemeyiz.
         * AdoNet yerine bu işlemleri bizim için oldukça kolaylaştıran ORM teknolojileri mevcuttur
         * ORM: Object Relational Mapping (Nesne-İlişkisel Eşleme) bu sistemde veritabanı nesneleri ile classlrımızı birbiriyle ilişkilendirip bunlar üzerinde rahatlıkla nesnel veri tabanı programlama yapılır
         * 
         * 1.Projeye eklemek için Project>ManageNuGetPackages>Browse> Entity Framework aratılarak yüklenir
         * Öncelikle tablomuzdaki alanların karşılıklarını tutan Product classını oluşturduk
         * Sonrasında tablomuzun karşılığı tutan Context class'ını oluşturduk
         * Projemizdeki App.config dosyasına giderek bağlantı adresimizi configsection'un altına ekledik (name, context name'mimizle aynı olmalı)
         * <connectionStrings>
              <add name="ETradeContext" connectionString="server=(localdb)\MSSQLLocalDB;initial catalog=ETrade;integrated security=true" providerName="System.Data.SqlClient"/>
           </connectionStrings>
         * //ETradeContext veri tabanıyla bağlantı kurmaya çalıştığında adresini App.config içerisindeki kendi ismiyle aynı (name=ETradeContext) bulup bağlantıyı sağlayacak
         */
        public Form1()
        {
            InitializeComponent();
        }

        ProductDal _productDal = new ProductDal();

        private void Form1_Load(object sender, EventArgs e)
        {
            /* //Biz Kodumuzu direk loada yazıp da çalıştırabiliriz ama CRUD işlemlerin yapıldığı bir sınıf oluşturup oradan çağırmak profesyonel manada kodu güçlendirir
            //SELECT (Entity)
            //EtradeContext pahallı bir nesne bellekte çok yer kaplıyor. Biz using kullanmadan ETradeContext context = new ETradeContext(); şeklinde de çağırabilirdik
            //using kullanarak nesnemizle işimiz bittiği anda Garbage Collector'u beklemeden, nesneyi zorla bellekten atıyoruz(dispose ediyoruz)            
            using (ETradeContext context = new ETradeContext())
            {
                dgwProducts.DataSource = context.Products.ToList();
            }
            */

            LoadProducts();
        }

        private void LoadProducts()
        {
            //SELECT
            dgwProducts.DataSource = _productDal.GetAll();
        }

        //INSERT
        private void btnAdd_Click(object sender, EventArgs e)
        {
            _productDal.Add(new Product
            {
                Name = tbxName.Text,
                UnitPrice = Convert.ToDecimal(tbxUnitPrice.Text),
                StockAmount = Convert.ToInt32(tbxStockAmount.Text)
            });
            LoadProducts();
            MessageBox.Show("Added!");
        }

        private void dgwProducts_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            tbxNameUpdate.Text = dgwProducts.CurrentRow.Cells[1].Value.ToString();
            tbxUnitPriceUpdate.Text = dgwProducts.CurrentRow.Cells[2].Value.ToString();
            tbxStockAmountUpdate.Text = dgwProducts.CurrentRow.Cells[3].Value.ToString();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            _productDal.Update(new Product
            {
                Id = Convert.ToInt32(dgwProducts.CurrentRow.Cells[0].Value),
                Name = tbxNameUpdate.Text,
                UnitPrice = Convert.ToDecimal(tbxUnitPriceUpdate.Text),
                StockAmount = Convert.ToInt32(tbxStockAmountUpdate.Text)
            });
            LoadProducts();
            MessageBox.Show("Updated!");
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            _productDal.Delete(new Product
            {
                Id = Convert.ToInt32(dgwProducts.CurrentRow.Cells[0].Value)
            }); 
            LoadProducts();
            MessageBox.Show("Deleted!");
        }
    }
}


Yorum bırakın

WordPress.com'da bir web sitesi veya blog oluşturun

Yukarı ↑

WordPress.com ile böyle bir site tasarlayın
Başlayın