<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Elchin Abraham</title>
    <description>The latest articles on DEV Community by Elchin Abraham (@elchinabraham).</description>
    <link>https://dev.to/elchinabraham</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1129233%2F77057db7-fe36-4ed4-ba2e-f1ef61d95a03.jpeg</url>
      <title>DEV Community: Elchin Abraham</title>
      <link>https://dev.to/elchinabraham</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/elchinabraham"/>
    <language>en</language>
    <item>
      <title>C# ilə məlumat bazası bağlantı əməliyyatları</title>
      <dc:creator>Elchin Abraham</dc:creator>
      <pubDate>Wed, 01 Nov 2023 07:43:06 +0000</pubDate>
      <link>https://dev.to/elchinabraham/c-il-mlumat-bazasi-baglanti-mliyyatlari-e2i</link>
      <guid>https://dev.to/elchinabraham/c-il-mlumat-bazasi-baglanti-mliyyatlari-e2i</guid>
      <description>&lt;p&gt;Proqram dünyasında hər bir proqram öz daxilində, yalnız, statik (statik - dəyişməyən) məlumatları saxlayır. Dinamik (dinamik - dəyişdirilə bilən) məlumatların saxlanılması üçün məlumat bazasından istifadə olunur. &lt;em&gt;&lt;strong&gt;Məlumat Bazası&lt;/strong&gt;&lt;/em&gt; - məlumatların saxlanılması, oxunması, dəyişdirilməsi və silinməsi əməliyyatlarını icra etmək üçün istifadə olunan bir texnologiyadır. MSSQL, MySQL, Oracle, PLSQL, PostgreSQL və s məlumat bazalarını nümumə çəkmək olar. Hər bir backend proqramlaşdırma dilinin spesifik xüsusiyyətlarindən biri də məlumat bazası bağlantısıdır. Bunun üçün bir nümunəyə baxaq. Yazacağımız nümunədə backend dili olaraq C#, məlumat bazası olaraq MSSQL - dən istifadə edəcəyik.&lt;/p&gt;

&lt;p&gt;Tutaq ki, bizə işçilərin məlumatlarını saxlamaq üçün kiçik bir proqram yazmaq tələb olunur. Sadəlik üçün işçilərə aid 3 məlumatı (Adı, doğum tarixi və telefon) qeyd edəcəyik. &lt;/p&gt;

&lt;p&gt;Əvvəlcə sql məlumat bazasında yeni bir baza yaradaq&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
CREATE DATABASE EmployeeDB

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Daha sonra bu məlumat bazasında Employees adında işcilər cədvəlini yaradaq.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
CREATE TABLE Employees
(
    Id VARCHAR(50) NOT NULL PRIMARY KEY,    -- İşçinin referans kodu
    FullName NVARCHAR(50) NOT NULL,         -- İşçinin tam adı
    BirthDate DATE NOT NULL,                -- İşçinin doğum tarixi
    Phone VARCHAR(20) NOT NULL              -- İşçinin telefon nömrəsi
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Cədvəlimiz də hazır olduqdan sonra artıq proqramı hazırlaya bilərik. Bunun üçün Visual Studio ortamından CSharp proqramlaşdırma dilini seçməklə, adını EmployeeService yazmaqla, yeni bir Console Application yaradırıq. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cu9ydvd0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tkuqn90ghj34f3kp8ka9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cu9ydvd0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tkuqn90ghj34f3kp8ka9.png" alt="Image description" width="800" height="530"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_5O433br--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3tmcruubcqcvouge13tj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_5O433br--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3tmcruubcqcvouge13tj.png" alt="Image description" width="800" height="522"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Biz məlumat bazası bağlantısı üçün SqlClient kitabxanasından istifadə edəcəyik. Bunun üçün proqramın Solution Explorer pəncərəsindən sağ düyməni sıxıb Manage NuGet Packages menyusuna daxil olub, SqlClient axtarışını edirik, System.Data.SqlClient kitabxanasın proqramımıza yükləyirik.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--agKuKQ8q--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7l0tmaj4rxuv89ui0c9l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--agKuKQ8q--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7l0tmaj4rxuv89ui0c9l.png" alt="Image description" width="800" height="667"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JLanqZXc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p0qs3ptq348tqqu00oo1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JLanqZXc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p0qs3ptq348tqqu00oo1.png" alt="Image description" width="800" height="337"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Proqramda məlumat bazasındakı işçi cədvəlini əks etdirmək üçün eyni ad və sütunlu klass yaradırıq.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
namespace EmployeeService
{
    internal class Employee
    {
        public string? Id { get; set; }

        public string? FullName { get; set; }

        public DateTime BirthDate { get; set; }

        public string? Phone { get; set; }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Əvvəlcə oxuma əməliyyatı üçün metodumuzu hazırlayaq.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
using EmployeeService;
using System.Data.SqlClient;

string connectionString = "data source=.; initial catalog=EmployeeDB; Integrated Security=True;";

List&amp;lt;Employee&amp;gt; GetEmployees()
{
    var employees = new List&amp;lt;Employee&amp;gt;();

    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();

        var query = "SELECT * FROM Employees";

        using (var command = new SqlCommand(query, connection))
        {
            using (var reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        var employee = new Employee
                        {
                            Id = reader.GetString(reader.GetOrdinal("Id")),
                            FullName = reader.GetString(reader.GetOrdinal("FullName")),
                            BirthDate = reader.GetDateTime(reader.GetOrdinal("BirthDate")),
                            Phone = reader.GetString(reader.GetOrdinal("Phone"))
                        };

                        employees.Add(employee);
                    }
                } 
            }
        }

        connection.Close();
    }

    return employees;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;İndi isə referans koduna görə axtarış ilə oxuma əməliyyatı üçün metod yazaq. Burada biz tək referans kodu deyil, digər sütunlara görə də axtarış icra edə bilərik.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
Employee GetEmployeeById(string id)
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();

        var query = "SELECT * FROM Employees WHERE Id = @id";

        using (var command = new SqlCommand(query, connection))
        {
            command.Parameters.AddWithValue("@id", id);

            using (var reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        var employee = new Employee
                        {
                            Id = reader.GetString(reader.GetOrdinal("Id")),
                            FullName = reader.GetString(reader.GetOrdinal("FullName")),
                            BirthDate = reader.GetDateTime(reader.GetOrdinal("BirthDate")),
                            Phone = reader.GetString(reader.GetOrdinal("Phone"))
                        };

                        return employee;
                    }
                }  
            }
        }

        connection.Close();
    }

    return null;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Növbəti əməliyyat yeni işçinin sistemə daxil edilməsi olsun.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void CreateEmployee(Employee newEmployee)
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();

        var query = "INSERT INTO Employees (Id, FullName, BirthDate, Phone) VALUES (@id, @fullName, @birthDate, @phone)";

        using (var command = new SqlCommand(query, connection))
        {
            command.Parameters.AddWithValue("@id", newEmployee.Id);
            command.Parameters.AddWithValue("@fullName", newEmployee.FullName);
            command.Parameters.AddWithValue("@birthDate", newEmployee.BirthDate);
            command.Parameters.AddWithValue("@phone", newEmployee.Phone);

            command.ExecuteNonQuery(); 
        }

        connection.Close();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sistemə daxil edilən məlumatlardan bir dəyişiklik ehtiyacı hər zaman yarana bilər. Bunun üçün məlumatı dəyişdirmək üçün bir metod yazaq.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
void UpdateEmployeeById(Employee newEmployee)
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();

        var query = "UPDATE Employees SET FullName = @fullName, BirthDate = @birthDate, Phone = @phone WHERE Id = @id";

        using (var command = new SqlCommand(query, connection))
        {
            command.Parameters.AddWithValue("@id", newEmployee.Id);
            command.Parameters.AddWithValue("@fullName", newEmployee.FullName);
            command.Parameters.AddWithValue("@birthDate", newEmployee.BirthDate);
            command.Parameters.AddWithValue("@phone", newEmployee.Phone);

            command.ExecuteNonQuery(); 
        }

        connection.Close();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Son olaraq məlumatın silinməsi metodunu yazaq.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
void DeleteEmployeeById(string id)
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();

        var query = "DELETE FROM Employees WHERE Id = @id";

        using (var command = new SqlCommand(query, connection))
        {
            command.Parameters.AddWithValue("@id", id);
            command.ExecuteNonQuery(); 
        }

        connection.Close();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Qeyd edək ki, hər bir işçi üçün referans kodu unique (unique - təkrarlanmayan) olduğundan silmə, dəyişdirmə və axtarış əməliyyatlarını referans kodu ilə etməklə xəta riskini azaltmış oluruq. &lt;/p&gt;

&lt;p&gt;İndi isə bu metodları ana proqramımızda istifadə edək.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// Yeni iscinin sisteme daxil edilmesi

var newEmployee = new Employee
{
    Id = Guid.NewGuid().ToString(),
    FullName = "Elcin Ibrahimli",
    BirthDate = DateTime.Parse("1994-10-14"),
    Phone = "+994503566919"
};

CreateEmployee(newEmployee);


// Butun iscilerin sistemden oxunmasi

var employees = GetEmployees();

foreach (var item in employees)
{
    Console.WriteLine($"Adi: {item.FullName}, Dogum Tarixi: {item.BirthDate}, Telefon: {item.Phone}");
}


// Iscinin axtaris edilmesi

var id = "{specifik_id}";

var employee = GetEmployeeById(id);


// Iscinin melumatinin deyisidirilmesi

var updatedEmployee = new Employee
{
    Id = "{specifik_id}",
    FullName = "Elchin Ibarhim",
    BirthDate = DateTime.Parse("1994-10-13"),
    Phone = "+9940503566919"
};

UpdateEmployeeById(updatedEmployee);

// iscinin sistemden silinmesi

id = "{specific_id}";

DeleteEmployeeById(id);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;QEYD:&lt;/strong&gt; Burada {specific_id} yeni işçi yaradılarkən Guid.NewGuid() metodunun yaradacağı referans kodudu. &lt;/p&gt;

</description>
    </item>
    <item>
      <title>C# - da inner type anlayışı</title>
      <dc:creator>Elchin Abraham</dc:creator>
      <pubDate>Tue, 26 Sep 2023 16:19:35 +0000</pubDate>
      <link>https://dev.to/elchinabraham/c-da-inner-type-anlayisi-eao</link>
      <guid>https://dev.to/elchinabraham/c-da-inner-type-anlayisi-eao</guid>
      <description>&lt;p&gt;Class daxilində field və ya metod saxlayan proqramçı tərəfindən hazırlanan bir obyektdir. C#-ın class daxilində başqa bir class yaratma kimi bir özəlliyi də var. Bu kimi class-lar nested class adlanır. C#-ın bu xüsusiyyəti proqram tərtibatçılarına class-ları qruplaşdırmaq, class-a kənardan müdaxilənin qarşısını almaq və proqram kodunu daha oxunaqlı hala gətirmək kimi bir imkanı verir. Bu  OYP - Obyekt Yönlü Proqramlaşdırmada (OOP - Object Oriented Programming) kapsülləmə (encapsulation) adlanır. Bir növ, class-a yalnız özü ilə eyni kod blokunda olan class-ların bağlanması təmin olunur, başqa class nested class-ı görmür.&lt;/p&gt;

&lt;p&gt;Nümunə:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ParentClass
{
    public void Method1()
    {
        Console.WriteLine("Method 1 was called in parent class");
    }

    class ChildClass
    {
        public void Method2() 
        { 
            Console.WriteLine("Method 2 was called in child class");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;İndi isə əsas ParentClass və ChildClass-ı Main metodunda istifadə edək.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--IVOdqfdq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nruc1snnol5aqrwtigzt.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IVOdqfdq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nruc1snnol5aqrwtigzt.PNG" alt="Image description" width="800" height="290"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Şəkildən göründüyü kimi 10-cu sətirdə proqramımız xəta ilə qarşılaşdı. Buna səbəb ParentClass-ın daxilindəki public olmayan bütün class-ları kapsülləməsi oldu. Bu bir növ kənardan ChildClass-a müdaxilənin qarşısın aldı. Tutaq ki, bizə belə bir tapşırıq qoyuldu ki, əsas proqramımızda ChildClass-ın Method2 metodunu çağıraq. Bunun üçün doğru üsul ParentClass-da bir metod yaradıb (məsələn: Method3), bu metod daxilində ChildClass-ın Method2 metodunu cağırmaq (yuxarıda dediyimiz kimi class daxilinə aldığı class-ın private olmayan bütün metodlarını görür) və ən sonda Main metodunda Method3 -ü çağırmaq olacaq.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ParentClass
{
    public void Method1()
    {
        Console.WriteLine("Method 1 was called in parent class");
    }

    class ChildClass
    {
        public void Method2() 
        { 
            Console.WriteLine("Method 2 was called in child class");
        }
    }

    public void Method3()
    {
        ChildClass c = new ChildClass();
        c.Method2();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ParentClass p =new ParentClass();
            p.Method1();

            p.Method3();    
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Əgər nested class-ın bağlantı göstəricisin public olaraq qeyd etsək bu class-a proqramın bütün yerlərindən qoşula bilərik.&lt;/p&gt;

&lt;p&gt;Nümunə:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ParentClass
{
    public void Method1()
    {
        Console.WriteLine("Method 1 was called in parent class");
    }

    public class ChildClass
    {
        public void Method2() 
        { 
            Console.WriteLine("Method 2 was called in child class");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ParentClass p =new ParentClass();
            p.Method1();

            ParentClass.ChildClass c = new ParentClass.ChildClass();
            c.Method2();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lakin bu üsul istifadə olunması tövsiyə edilməyən üsuldur. Çünki, əgər, nested class daxilində həssas məlumatlar saxlayarsa (məsələn: istifadəçi kodu) proqramın digər class-larından asanlıqla bu məlumatı əldə etmək və ya dəyişdirmək kimi proqram tətbiqinin boşluqları olar.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>C# - da property anlayışı</title>
      <dc:creator>Elchin Abraham</dc:creator>
      <pubDate>Sun, 06 Aug 2023 11:10:47 +0000</pubDate>
      <link>https://dev.to/elchinabraham/c-da-property-anlayisi-4lmm</link>
      <guid>https://dev.to/elchinabraham/c-da-property-anlayisi-4lmm</guid>
      <description>&lt;p&gt;Obyekt yönümlü proqramlaşdırma dillərində mövcud olan property anlayışı C# dilində də sıx istifadə olunmaqdadır. Property nə üçün istifadə olunur qısa bir nümunə üzərindən araşdıraq.&lt;/p&gt;

&lt;p&gt;Təsəvvür edək ki, bizim Human adlı bir klasımız var. Sadəlik üçün bu klasın sadəcə bir global dəyişəni var ki, bu dəyişən Human klasının yaş məlumatın özündə əks etdirir.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JHzVMSnH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ngdrm5qhmj4g4013u9cz.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JHzVMSnH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ngdrm5qhmj4g4013u9cz.PNG" alt="Image description" width="761" height="256"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Bu klası proqramın ana metodu olan Main metodunda istifadə edək.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--CfAj0QFT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g6st6cm1xp291ybv463j.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--CfAj0QFT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g6st6cm1xp291ybv463j.PNG" alt="Image description" width="800" height="419"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yuxarıdakı şəkildən də göründüyü kimi Main metodunda Human klasımızın instance-ın yaratdıq və bu instance vasitəsi ilə Human klasındakı public olan dəyişənləri görə bildik. Burada Human klasın adı, h dəyişəni Human klasın instance-ı, Age isə Human klasın public dəyişənidir. Sadəlik üçün alqoritmik hesablamaları və məlumat bazası (database) bağlantılarının üzərindən keçək və təsəvvür edək ki, daxil etdiyimiz yaş (28) məlumat bazasına yazılır. Bura qədər hər şey aydındır. &lt;/p&gt;

&lt;p&gt;İndi isə gəlin təsəvvür edək ki, istifadəçi tərəfindən daxil edilən yaş -1 kimidir. O zaman bizim proqramımız h.Age məlumatını mənfi ədəd kimi alacaq və məlumat bazasına -1 yazılacaq. Bu da proqramın başqa proseslərini zədələyəcək. Məsələn, yaşla əlaqədar bir layihə düşünün və təqaüdün hesablanması zamanı yaşdan istifadə olunur və təqaüd məbləği hesablanarkən yekun cavabda mənfi ədəd alınır. Bu kimi halın qarşısını almaq üçün təbii olaraq biz if operatorundan istifadə edə bilərik. Məsələn:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RbQXeKdB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgwn9c3qhgdsmamadg0q.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RbQXeKdB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgwn9c3qhgdsmamadg0q.PNG" alt="Image description" width="800" height="244"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Əgər təsəvvür etsək ki, proqramımızda Human klasının Age dəyişənininə bir çox yerdə yaş məlumatı yazırıq, o zaman biz gərək hər dəfə yaş məlumatını yazmamışdan öncə if şərt operatorunu yazaq. Qısası bu üsul optimal üsul sayılmaz. Bu problemin həll olunmasında property anlayışı yardımımıza gəlir. Bunun üçün Human klasımızda Age dəyişəninin adını property-dən fərqləndirmək üçün age olaraq dəyişirik və public bağlantı göstəricisini private olaraq dəyişirik. Əlavə olaraq da property yaradırıq.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EAe0XprL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m9mweyfq7jqy685hgelb.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EAe0XprL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m9mweyfq7jqy685hgelb.PNG" alt="Image description" width="800" height="455"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Burada age dəyişən, Age isə property adlanır. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Zu4Uayr0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/siz42kvr20cvjpexss88.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Zu4Uayr0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/siz42kvr20cvjpexss88.PNG" alt="Image description" width="800" height="341"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Artıq Main metodunda yaş məlumatı daxil edərkən if şərt operatoruna ehtiyac qalmadı. Bu şərti biz property daxilində set funksiyası zamanı edirik. Set funksiyası daxilindəki value parametri istifadəçi tərəfindən daxil edilən yaş məlumatıdır. Yekun olaraq biz age dəyişənimizi private edərək onu Human klasından başqa proqramın bütün hissələri üçün bağladıq. Bunun əvəzinə age dəyişəninə məlumat yazmaq və məlumat oxumaq üçün Age property-si yaratdıq. Bu property daxilində bir dəfə if şərt operatorunu yazmaqla bütün proqramda kod qısalmasına səbəb olduq. 9 dəfə yaş məlumatını yazmağımıza rəğmən, property vasitəsi ilə bir if şərt operatorundan istifadə etdik. Bu cür bağlanma, yəni ki, dəyişənin public-dən private-a keçməsi obyekt yönlü proqramlaşdırmada kapsülləmə (Encapsulation) adlanır.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--FTxi8ZV6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0wbgwt0ch2zk9k14qbre.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--FTxi8ZV6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0wbgwt0ch2zk9k14qbre.PNG" alt="Image description" width="800" height="546"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Indi isə təsəvvür edək ki, Human class-ımızda əlavə olaraq Temperature dəyişəni var və bu dəyişən həm mənfi, həm də mübət qiymət ala bilər, dolayısı ilə heç bir şərt operatoruna ehtiyacımız yoxdur. Bu durumda artıq propety və public dəyişəni qısa formada aşağıdakı kimi yaza bilərik.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kXvFmNQ4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hfgxnhcj0qgm5j68lw2.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kXvFmNQ4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hfgxnhcj0qgm5j68lw2.PNG" alt="Image description" width="793" height="732"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Why do we need method in any programming language?</title>
      <dc:creator>Elchin Abraham</dc:creator>
      <pubDate>Sun, 30 Jul 2023 11:40:13 +0000</pubDate>
      <link>https://dev.to/elchinabraham/why-do-we-need-method-in-any-programming-language-1o5n</link>
      <guid>https://dev.to/elchinabraham/why-do-we-need-method-in-any-programming-language-1o5n</guid>
      <description>&lt;p&gt;&lt;strong&gt;What is method?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Methods is exists almost all programming language. It prevents code duplication and makes program code more readable. There are two most important point for methods - input parameter and return type. A method may have a sequence of parameters. Parameters define the set of arguments that must be provided for that method. We will use C# syntax for examples. For example&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--D0qhouXe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m31l36b6z9jn75rt31sp.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--D0qhouXe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m31l36b6z9jn75rt31sp.PNG" alt="Image description" width="795" height="294"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It is access specifiers. It define method accessibility&lt;/li&gt;
&lt;li&gt;Return type&lt;/li&gt;
&lt;li&gt;It is method name that you can give any name&lt;/li&gt;
&lt;li&gt;These are input parameter list&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the following example, the method Foo has a single parameter named p, of type int&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Foo (8); // 8 is an argument
static void Foo (int p) {...} // p is a parameter
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Methods can declare optional parameters. A parameter is optional if it specifies a default value in its declaration. You can omit optional parameters when calling the method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void Foo (int x = 23) 
{ 
    Console.WriteLine (x); 
}
Foo(); // 23
Foo(12); // 12
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rather than identifying an argument by position, you can identify an argument by name. It is called Named arguments. Named arguments can occur in any order. The following calls to Foo are semantically identical&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void Foo (int x, int y) 
{ 
    Console.WriteLine (x + ", " + y); 
}

Foo (x:1, y:2);
Foo (y:2, x:1);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Why do we need method?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's approach to this question over simple task. Let's suppose that two numbers which are integers were given. We need to check which one of is bigger? If first number is bigger than second one, we should calculate multiplication between this numbers and sum of digits of same numbers. If second number is bigger than first one or they are equal, we should calculate addition between this numbers and sum of digits of same numbers. At last compare results. Which one of is bigger? For example:&lt;/p&gt;

&lt;p&gt;12 and 23&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;12 is not bigger than 23 then&lt;/li&gt;
&lt;li&gt;23 is bigger than 12 then
 12 + (1 + 2) = 15 and 23 + (2 + 3) = 28&lt;/li&gt;
&lt;li&gt;15 and 28 =&amp;gt; Result: 28 (bigger than 15)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's write this algorithm without method in C#:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int firstNumber = int.Parse(Console.ReadLine());
int secondNumber = int.Parse(Console.ReadLine());

if (firstNumber &amp;gt; secondNumber)
{
    // Find sum of digits of first number
    int sumOfFirstNumber = 0;
    int firstTempNumber = firstNumber;

    while (firstTempNumber &amp;gt; 0)
    {
        int lastDigit = firstTempNumber % 10;
        sumOfFirstNumber += lastDigit;
        firstTempNumber /= 10;
    }

    // Find sum of digits of second number
    int sumOfSecondNumber = 0;
    int secondTempNumber = secondNumber;

    while (secondTempNumber &amp;gt; 0)
    {
        int lastDigit = secondTempNumber % 10;
        sumOfSecondNumber += lastDigit;
        secondTempNumber /= 10;
    }

    int resultFirst = firstNumber * sumOfFirstNumber;
    int resultSecond = secondNumber * sumOfSecondNumber;

    if (resultFirst &amp;gt; resultSecond)
    {
        Console.WriteLine(resultFirst);
    }
    else
    {
        Console.WriteLine(resultSecond);
    }
}
else
{
    // Find sum of digits of first number
    int sumOfFirstNumber = 0;
    int firstTempNumber = firstNumber;

    while (firstTempNumber &amp;gt; 0)
    {
        int lastDigit = firstTempNumber % 10;
        sumOfFirstNumber += lastDigit;
        firstTempNumber /= 10;
    }

    // Find sum of digits of second number
    int sumOfSecondNumber = 0;
    int secondTempNumber = secondNumber;

    while (secondTempNumber &amp;gt; 0)
    {
        int lastDigit = secondTempNumber % 10;
        sumOfSecondNumber += lastDigit;
        secondTempNumber /= 10;
    }

    int resultFirst = firstNumber + sumOfFirstNumber;
    int resultSecond = secondNumber + sumOfSecondNumber;

    if (resultFirst &amp;gt; resultSecond)
    {
        Console.WriteLine(resultFirst);
    }
    else
    {
        Console.WriteLine(resultSecond);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's try to make more simple via using method. Firstly, create 2 methods which return sum of digits of number and compare 2 numbers and print screen to max one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int FindSumOfDigitsOfNumber(int number)
{
    int result = 0;

    while (number &amp;gt; 0)
    {
        int lastDigit = number % 10;
        result += lastDigit;
        number /= 10;
    }

    return result;
}

void FindMaxNumberAndPrint(int first, int second)
{
    if (first &amp;gt; second)
    {
        Console.WriteLine(first);
    }
    else
    {
        Console.WriteLine(second);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we can write our main code as following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int firstNumber = int.Parse(Console.ReadLine());
int secondNumber = int.Parse(Console.ReadLine());

if (firstNumber &amp;gt; secondNumber)
{
    // Find sum of digits of first number
    int sumOfFirstNumber = FindSumOfDigitsOfNumber(firstNumber);

    // Find sum of digits of second number
    int sumOfSecondNumber = FindSumOfDigitsOfNumber(secondNumber);

    int resultFirst = firstNumber * sumOfFirstNumber;
    int resultSecond = secondNumber * sumOfSecondNumber;

    FindMaxNumberAndPrint(resultFirst, resultSecond);
}
else
{
    // Find sum of digits of first number
    int sumOfFirstNumber = FindSumOfDigitsOfNumber(firstNumber);

    // Find sum of digits of second number
    int sumOfSecondNumber = FindSumOfDigitsOfNumber(secondNumber);

    int resultFirst = firstNumber + sumOfFirstNumber;
    int resultSecond = secondNumber + sumOfSecondNumber;

    FindMaxNumberAndPrint(resultFirst, resultSecond);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is simple example and if you are software developer, you will face much more difficult tasks than this one during working. Every time when you use method, it will make your code more readable and short.&lt;/p&gt;

&lt;p&gt;Best regards...&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Dapper in ASP.NET Core with Repository Pattern</title>
      <dc:creator>Elchin Abraham</dc:creator>
      <pubDate>Sun, 30 Jul 2023 08:05:07 +0000</pubDate>
      <link>https://dev.to/elchinabraham/dapper-in-aspnet-core-with-repository-pattern-2n33</link>
      <guid>https://dev.to/elchinabraham/dapper-in-aspnet-core-with-repository-pattern-2n33</guid>
      <description>&lt;p&gt;In this article, we will learn all about Dapper in ASP.NET Core and make a small implementation to understand how it works. Let’s not limit it just to Dapper. We will build an application that follows a very simple and clean architecture. In this implementation, we will try to under Repository Pattern and Unit Of Work as well. Everything put together, this article helps you to understand How Dapper can be used in an ASP.NET Core Application following Repository Pattern and Unit of Work.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating the MS-SQL Database and Table&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s create our Database and Related Table First. Open up SQL Management Studio and connect to your local SQL Server. Execute following sql commands senquentially.&lt;/p&gt;

&lt;p&gt;command 1:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE DATABASE TEST
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command creates new database named TEST. Then select TEST database from Aviables Database list and execute next sql command&lt;/p&gt;

&lt;p&gt;command 2:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE Stocks
(
    [Id] INT NOT NULL IDENTITY PRIMARY KEY,
    [Code] VARCHAR(10) NOT NULL,
    [Description] NVARCHAR(100) NOT NULL
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have created simple table because of I have tried to make simplest example for all flow.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Getting Started with ASP.NET Core WebApi Project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's create new project in Visual Studio as following. Let's name Stocks.WebApi to project name and Stocks to solution name.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6vsgm38teqyeeq3c6ynr.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6vsgm38teqyeeq3c6ynr.PNG" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy0w4o5bxiu6zwk4e83cw.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy0w4o5bxiu6zwk4e83cw.PNG" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then we should add 3 new projects Stocks.Core, Stocks.Repository and Stocks.Service to our Stocks solution how I did in following images. In every time when we create new projects which is class library, it creates new class named class1 by default. Let's remove all class1 classes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo9mvjt68z4jos9bcfmr9.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo9mvjt68z4jos9bcfmr9.PNG" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe5cw0wqb34ty4rqre3in.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe5cw0wqb34ty4rqre3in.PNG" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4zkicv9a9xrjs7jqml7i.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4zkicv9a9xrjs7jqml7i.PNG" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we can setup our interfaces and classes. Firstly, let's add new Stock class to our Stocks.Core project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Stock
    {
        public int Id { get; set; }
        public string Code { get; set; }
        public string Description { get; set; }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Remember, The Core layer is not going to depend on any other Project / Layer. This is very important while following Onion Architecture.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next, Add another .NET Core Library Project and name it Stocks.Repository. This is the Repository Layer, that has the interfaces defined. So what will happen is, we define the interfaces for Repositories here, and implement these interfaces at another layer that is associated with Data access.&lt;/p&gt;

&lt;p&gt;Create a new interface, IGenericRepository.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IGenericRepository&amp;lt;T&amp;gt; where T : class
{
    Task&amp;lt;T&amp;gt; GetByIdAsync(int id);
    Task&amp;lt;IReadOnlyList&amp;lt;T&amp;gt;&amp;gt; GetAllAsync();
    Task&amp;lt;int&amp;gt; AddAsync(T entity);
    Task&amp;lt;int&amp;gt; UpdateAsync(T entity);
    Task&amp;lt;int&amp;gt; DeleteAsync(int id);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will be using Repository Pattern along with the Unit Of work in our Implementation. In IGenericRepository, we are building a generic definition for the repository pattern. These include the most commonly used CRUD Operations like GetById, GetAll, Add, Update and Delete.&lt;/p&gt;

&lt;p&gt;Now that we have a generic Interface, let’s build the Stock Specific Repository Interface. Add a new interface and name it IStockRepository. We will Inherit the IGenericRepository Interface with T as the Stock. Finally, add the last Interface, IUnitOfWork.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IUnitOfWork
{
        IStockRepository Stocks { get; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we need to define the connection string of our database, so that the application can connect to our Database for performing CRUD operations. Open up the appsettings.json file in the Stocks.WebApi Project and add the following&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=TEST;Integrated Security=True;"
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then let's call following console commands in Stocks.Service project. Select Tools menu in Visual Studio, select NuGet Package Manager and then select Package Manager Console. Make sure Stocks.Service is selected in Default project dropdown list. Then execute following commands sequentially.&lt;/p&gt;

&lt;p&gt;command 1:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Install-Package Dapper
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;command 2:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Install-Package Microsoft.Extensions.Configuration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;command 3:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Install-Package Microsoft.Extensions.DependencyInjection.Abstractions
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;command 4:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Install-Package System.Data.SqlClient
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then add StockService class to Stocks.Service project as following.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class StockService : IStockRepository
    {
        private readonly IConfiguration configuration;
        public StockService(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        public async Task&amp;lt;int&amp;gt; AddAsync(Stock entity)
        {
            var sql = "Insert into Stocks (Code,Description) VALUES (@Code,@Description)";
            using (var connection = new SqlConnection(configuration.GetConnectionString("DefaultConnection")))
            {
                connection.Open();
                var result = await connection.ExecuteAsync(sql, entity);
                return result;
            }
        }

        public async Task&amp;lt;int&amp;gt; DeleteAsync(int id)
        {
            var sql = "DELETE FROM Stocks WHERE Id = @Id";
            using (var connection = new SqlConnection(configuration.GetConnectionString("DefaultConnection")))
            {
                connection.Open();
                var result = await connection.ExecuteAsync(sql, new { Id = id });
                return result;
            }
        }

        public async Task&amp;lt;IReadOnlyList&amp;lt;Stock&amp;gt;&amp;gt; GetAllAsync()
        {
            var sql = "SELECT * FROM Stocks";
            using (var connection = new SqlConnection(configuration.GetConnectionString("DefaultConnection")))
            {
                connection.Open();
                var result = await connection.QueryAsync&amp;lt;Stock&amp;gt;(sql);
                return result.ToList();
            }
        }

        public async Task&amp;lt;Stock&amp;gt; GetByIdAsync(int id)
        {
            var sql = "SELECT * FROM Stocks WHERE Id = @Id";
            using (var connection = new SqlConnection(configuration.GetConnectionString("DefaultConnection")))
            {
                connection.Open();
                var result = await connection.QuerySingleOrDefaultAsync&amp;lt;Stock&amp;gt;(sql, new { Id = id });
                return result;
            }
        }

        public async Task&amp;lt;int&amp;gt; UpdateAsync(Stock entity)
        {
            var sql = "UPDATE Stocks SET Code = @Code, Description = @Description WHERE Id = @Id";
            using (var connection = new SqlConnection(configuration.GetConnectionString("DefaultConnection")))
            {
                connection.Open();
                var result = await connection.ExecuteAsync(sql, entity);
                return result;
            }
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, Let’s implement the IUnitOfWork. Create a new class, UnitOfWork, and inherit from the interface IUnitOfWork.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class UnitOfWork : IUnitOfWork
    {
        public UnitOfWork(IStockRepository stockRepository)
        {
            Stocks = stockRepository;
        }

        public IStockRepository Stocks { get; }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, go to the program.cs (Startup.cs/ConfigureServices method in project which's version unders NET 5) in the WebApi Project, and let’s call the above-made extension method.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;builder.Services.AddTransient&amp;lt;IStockRepository, StockService&amp;gt;();&lt;br&gt;
builder.Services.AddTransient&amp;lt;IUnitOfWork, UnitOfWork&amp;gt;();&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In the WebApi Project, Add a new Controller under the Controllers folder. Let’s name it Stock Controller.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Route("api/[controller]")]
    [ApiController]
    public class StockController : ControllerBase
    {
        private readonly IUnitOfWork unitOfWork;
        public StockController(IUnitOfWork unitOfWork)
        {
            this.unitOfWork = unitOfWork;
        }

        [HttpGet]
        public async Task&amp;lt;IActionResult&amp;gt; GetAll()
        {
            var data = await unitOfWork.Stocks.GetAllAsync();
            return Ok(data);
        }

        [HttpGet("{id}")]
        public async Task&amp;lt;IActionResult&amp;gt; GetById(int id)
        {
            var data = await unitOfWork.Stocks.GetByIdAsync(id);
            if (data == null) return Ok();
            return Ok(data);
        }

        [HttpPost]
        public async Task&amp;lt;IActionResult&amp;gt; Add(Stock stock)
        {
            var data = await unitOfWork.Stocks.AddAsync(stock);
            return Ok(data);
        }

        [HttpDelete]
        public async Task&amp;lt;IActionResult&amp;gt; Delete(int id)
        {
            var data = await unitOfWork.Stocks.DeleteAsync(id);
            return Ok(data);
        }

        [HttpPut]
        public async Task&amp;lt;IActionResult&amp;gt; Update(Stock stock)
        {
            var data = await unitOfWork.Stocks.UpdateAsync(stock);
            return Ok(data);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we can test our projects with swagger which is default start page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd3u13x87gyzpnepu8584.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd3u13x87gyzpnepu8584.PNG" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I hope you learned something new and detailed in this article. If you have any comments or suggestions, please leave them behind in the comments section below. Do not forget to share this article within your developer community. Thanks and Happy Coding!&lt;/p&gt;

&lt;p&gt;Best regards...&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
