1-) .Net 6 Core Web Api - Helper Oluşturma RawSqlQuery
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
namespace StudentAutomation.DataAccess.Concrete
{
public static class Helper
{
public static List<T> RawSqlQuery<T>(string query, Func<DbDataReader, T> map)
{
using (var context = new StudentAutomationDbContext())
{
using (var command = context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = query;
command.CommandType = CommandType.Text;
context.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
var entities = new List<T>();
while (result.Read())
{
entities.Add(map(result));
}
return entities;
}
}
}
}
}
}
KULLANIMI
var result = Helper.RawSqlQuery(
"SELECT TOP 10 Name, COUNT(*) FROM Users U"
+ " INNER JOIN Signups S ON U.UserId = S.UserId"
+ " GROUP BY U.Name ORDER BY COUNT(*) DESC",
x => new TopUser { Name = (string)x[0], Count = (int)x[1] });
result.ForEach(x => Console.WriteLine($"{x.Name,-25}{x.Count}"));
DİĞER
public class StudentAutomationRepository : IStudentAutomationRepository
{
public List<Student> AllStudentList()
{
using (var studentAutomationDbContext = new StudentAutomationDbContext())
{
var posKodlarModels = Helper.RawSqlQuery("Select FirstName from Students", x=> new Student() { FirstName= (string)x[0] });
return studentAutomationDbContext.Students.ToList();
}
}
...}