🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / C# RMOS / .Net Core 8 Web Api ve Dapper Kullanımı 2 interfaces ve unitofwork

1-) C# RMOS - .Net Core 8 Web Api ve Dapper Kullanımı 2 interfaces ve unitofwork

 

bu şekilde yazarsan swagger de gözükmez

[ApiExplorerSettings(IgnoreApi = true)]

        [NonAction]

 

 

SQL BAĞLANTI HATASI ALIRSAN BUNU ÇALIŞTIR

 

 public class DatabaseConnections

 {

     public IDbConnection DefaultConnection { get; }

     public DatabaseConnections(IDbConnection defaultConnection)

     {

         DefaultConnection = defaultConnection;

         DefaultConnection.Open();

     }

 }

 

 

 

 

public async Task<IEnumerable<object>> GetAllAsync4()

 {

     var notlar = await _connection.QueryAsync("SELECT * FROM notlar");

 

     foreach (var item in notlar)

     {

         string ad = item.ad;

     }

 

     return notlar;

 }

 

 

 

C# .Net Core 8 Api kullanarak Unitofwork Design pattern ve Dapper ile BASİT CRUD işlemleri



 

github link : https://github.com/ramazanhaber/NetCore8ApiDapper

 

youtube link : https://youtu.be/gHdEIkYvFBM

 

1. kurulması gerekenler

 Install-Package Microsoft.EntityFrameworkCore.SqlServer

 Install-Package Dapper.Contrib

 Install-Package Microsoft.AspNetCore.Authentication.JwtBearer

 Install-Package Newtonsoft.Json

 

1. Adım Helper -> DatabaseConnections.cs

 

 

public class DatabaseConnections

{

    public IDbConnection DefaultConnection { get; }

    public IDbConnection SecondConnection { get; }

    public DatabaseConnections(IDbConnection defaultConnection, IDbConnection secondConnection)

    {

        DefaultConnection = defaultConnection;

        SecondConnection = secondConnection;

    }

}

 

 

2. Adım Models -> Ogrenciler.cs

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

 

namespace Netcore8_test.Models

{

    [Table("Ogrenciler")]

    public class Ogrenciler

    {

        [Key]

        public int id { get; set; }

        public string ad { get; set; }

        public int yas { get; set; }

    }

}

 

 

3. Adım Interfaces-> IGenericRepository.cs

 

namespace Netcore8_test.Interfaces

{

    public interface IGenericRepository<T> where T : class

    {

        Task<T> GetByIdAsync(int id);

        Task<IEnumerable<T>> GetAllAsync();

        Task<int> AddAsync(T entity);

        Task<bool> UpdateAsync(T entity);

        Task<bool> DeleteAsync(int id);

    }

}

 

 

4. Adım Interfaces-> IOgrencilerRepository.cs

using Netcore8_test.Models;

 

namespace Netcore8_test.Interfaces

{

    public interface IOgrencilerRepository : IGenericRepository<Ogrenciler>

    {

    }

}

 

5. Adım Interfaces-> IUnitOfWork.cs

namespace Netcore8_test.Interfaces

{

    public interface IUnitOfWork

    {

        IOgrencilerRepository Ogrenciler { get; }

    }

}

 

 

6. Adım Repository-> GenericRepository.cs

 

using Dapper.Contrib.Extensions;

using Netcore8_test.Helper;

using Netcore8_test.Interfaces;

using System.Data;

 

namespace Netcore8_test.Repository

{

    public class GenericRepository<T> : IGenericRepository<T> where T : class

    {

 

        private readonly IDbConnection _connection;

        private readonly IConfiguration _configuration;

 

        public GenericRepository(DatabaseConnections connections, IConfiguration configuration)

        {

            _connection = connections.DefaultConnection;

            _configuration = configuration;

        }

 

        public async Task<int> AddAsync(T entity)

        {

            return await _connection.InsertAsync(entity);

        }

 

        public async Task<bool> DeleteAsync(int id)

        {

            var entityToDelete = await _connection.GetAsync<T>(id);

            if (entityToDelete != null)

            {

                return await _connection.DeleteAsync(entityToDelete);

            }

            return false;

        }

 

        public async Task<IEnumerable<T>> GetAllAsync()

        {

            return await _connection.GetAllAsync<T>();

        }

 

        public async Task<T> GetByIdAsync(int id)

        {

            return await _connection.GetAsync<T>(id);

        }

 

        public async Task<bool> UpdateAsync(T entity)

        {

            return await _connection.UpdateAsync(entity);

        }

    }

 

}

 

 

 

7. Adım Repository-> OgrencilerRepository.cs

using Dapper.Contrib.Extensions;

using Netcore8_test.Helper;

using Netcore8_test.Interfaces;

using Netcore8_test.Models;

using System.Data;

namespace Netcore8_test.Repository

{

    public class OgrencilerRepository : GenericRepository<Ogrenciler>, IOgrencilerRepository

    {

        public OgrencilerRepository(DatabaseConnections connections, IConfiguration configuration) : base(connections, configuration)

        {

        }

    }

}

 

 

 

8. Adım Repository-> UnitOfWork.cs

 

using Netcore8_test.Interfaces;

 

namespace Netcore8_test.Repository

{

    public class UnitOfWork : IUnitOfWork

    {

 

        public UnitOfWork(IOgrencilerRepository ogrenciler)

        {

            this.Ogrenciler = ogrenciler;

        }

        public IOgrencilerRepository Ogrenciler { get; }

    }

}

 

 

9. Adım -> appsettings.json

{

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft.AspNetCore": "Warning"

    }

  },

  "ConnectionStrings": {

    "DefaultConnection": "Server=RAMBO3;Database=Deneme1;User ID=sa;Password=şifre;TrustServerCertificate=true;",

 

    "SecondConnection": "Server=RAMBO3;Database=Deneme2;User ID=sa;Password=şifre;TrustServerCertificate=true;"

  },

  "AllowedHosts": "*"

}

 

 

10. Adım -> Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;

using Microsoft.AspNetCore.ResponseCompression;

using Microsoft.Data.SqlClient;

using Microsoft.IdentityModel.Tokens;

using Microsoft.OpenApi.Models;

using Netcore8_test.Helper;

using Netcore8_test.Interfaces;

using Netcore8_test.Repository;

using System.Data;

using System.IO.Compression;

using System.Text;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

/*

 KURULMASI GEREKEN NUGETLER

 

 Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 8.0.1

 Install-Package Dapper.Contrib -Version 2.0.78

 Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 8.0.1

 Install-Package Newtonsoft.Json -Version 13.0.3

 */

 

string defaultConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");

 

IDbConnection defaultConnection = new SqlConnection(defaultConnectionString);

 

string secondConnectionString = builder.Configuration.GetConnectionString("SecondConnection");

 

IDbConnection secondConnection = new SqlConnection(secondConnectionString);


builder.Services.AddSingleton(new DatabaseConnections(defaultConnection, secondConnection));

 

builder.Services.AddScoped<IOgrencilerRepository, OgrencilerRepository>();

builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();


builder.Services.Configure<GzipCompressionProviderOptions>(options =>

{

    options.Level = CompressionLevel.Fastest;

});

 

builder.Services.AddResponseCompression(options =>

{

    options.EnableForHttps = true;

    options.Providers.Add<GzipCompressionProvider>();

});

 

var app = builder.Build();

 

app.UseResponseCompression();

 

app.UseCors(builder => builder

.AllowAnyHeader()

.AllowAnyMethod()

.AllowAnyOrigin()

);

 

if (app.Environment.IsDevelopment() || app.Environment.IsProduction())

{

    app.UseDeveloperExceptionPage();

    app.UseSwagger();

    app.UseSwaggerUI(c => {

        c.SwaggerEndpoint("/swagger/v1/swagger.json", "myapi v1");

    });

}

 

app.UseHttpsRedirection();

app.UseAuthentication();// auth iin

app.UseAuthorization();

app.MapControllers();

app.Run();

 

 

11. adım Controller -> OgrencilerController.cs

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using NetCore8ApiDapper.Interfaces;

using NetCore8ApiDapper.Models;

 

namespace NetCore8ApiDapper.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class OgrencilerController : ControllerBase

    {

        private readonly IUnitOfWork unitOfWork;

 

        public OgrencilerController(IUnitOfWork unitOfWork)

        {

            this.unitOfWork = unitOfWork;

        }

 

        [HttpGet]

        [Route("GetOgrenciler")]

        public async Task<ActionResult<IEnumerable<Ogrenciler>>> GetOgrenciler()

        {

            var ogrenciler = await unitOfWork.Ogrenciler.GetAllAsync();

            return Ok(ogrenciler);

        }

 

        [HttpPost]

        [Route("AddOgrenci")]

        public async Task<IActionResult> AddOgrenci(Ogrenciler ogrenci)

        {

            await unitOfWork.Ogrenciler.AddAsync(ogrenci);

            return Ok();

        }

        [HttpPost]

        [Route("UpdateOgrenci")]

        public async Task<IActionResult> UpdateOgrenci(Ogrenciler ogrenci)

        {

            await unitOfWork.Ogrenciler.UpdateAsync(ogrenci);

            return Ok();

        }

        [HttpPost]

        [Route("DeleteOgrenci")]

        public async Task<IActionResult> DeleteOgrenci(int id)

        {

            var result = await unitOfWork.Ogrenciler.DeleteAsync(id);

            return result ? Ok() : NotFound();

        }

 

    }

}

 

 

 

 

 

AYRICA BAKINIZ

açıklama : iGeneric olmayan bir metot daha yazmak istersem bu şekilde yapabilirim (GetAllAsync2 ve GetAllAsync3 şeklinde)

 

 public interface INotlarRepository: IGenericRepository<Notlar>

 {

     Task<IEnumerable<object>> GetAllAsync2();

     Task<IEnumerable<Notlar>> GetAllAsync3();

 }

 

public class NotlarRepository : GenericRepository<Notlar>, INotlarRepository

{

    private readonly IDbConnection _connection;

 

    public NotlarRepository(DatabaseConnections connections, IConfiguration configuration) : base(connections, configuration)

    {

        _connection = connections.DefaultConnection; // ilk veri tabanı

 

    }

 

    public async Task<IEnumerable<object>> GetAllAsync2()

    {

        var notlar = await _connection.QueryAsync<object>("SELECT *,'selamlar' as naber FROM notlar");

        return notlar;

    }

 

    public async Task<IEnumerable<Notlar>> GetAllAsync3()

    {

        var notlar = await _connection.QueryAsync<Notlar>("SELECT * FROM notlar");

        return notlar;

    }

}

 

 

  [Route("api/[controller]")]

  [ApiController]

  public class NotlarController : ControllerBase

  {

      private readonly IUnitOfWork unitOfWork;

      private readonly IDbConnection _connection;

 

      public NotlarController(DatabaseConnections connections, IUnitOfWork unitOfWork)

      {

          this.unitOfWork = unitOfWork;

          _connection = connections.DefaultConnection; // ilk veri tabanı

 

      }

    [HttpPost]

    [Route("notlarilistele")]

    public async Task<IActionResult> notlarilistele()

    {

        var notlarler = await unitOfWork.Notlar.GetAllAsync2();

        return Ok(notlarler);

    }

 

    [HttpPost]

    [Route("notlarilistele2")]

    public async Task<IActionResult> notlarilistele2()

    {

        var notlarler = await unitOfWork.Notlar.GetAllAsync3();

        return Ok(notlarler);

    }

 

}

 

 2024 Haziran 03 Pazartesi
 477