[성현모] TRA DB목록 불러오기, 정의 자동추가
This commit is contained in:
56
Projects/SystemX.Core/SystemX.Core/DB/DBStoredProcedure.cs
Normal file
56
Projects/SystemX.Core/SystemX.Core/DB/DBStoredProcedure.cs
Normal file
@ -0,0 +1,56 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Core.DB
|
||||
{
|
||||
public static class DBStoredProcedure
|
||||
{
|
||||
public static async Task<IEnumerable<TResult>>? ExecuteStoredProcedureAsync<TEntity, TResult>(this DbContext dbContext, string storedProcedure) where TEntity : class where TResult : class
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = new List<TResult>();
|
||||
var type = typeof(TResult);
|
||||
|
||||
using var command = dbContext.Database.GetDbConnection().CreateCommand();
|
||||
command.CommandText = storedProcedure;
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
if (command.Connection.State != ConnectionState.Open)
|
||||
await command.Connection.OpenAsync();
|
||||
|
||||
using var reader = await command.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
TResult row = (TResult)Activator.CreateInstance(typeof(TResult));
|
||||
|
||||
foreach (var prop in type.GetProperties())
|
||||
{
|
||||
string propertyName = $"{prop.Name}";
|
||||
var value = reader.GetValue(propertyName);
|
||||
prop.SetValue(row, value);
|
||||
}
|
||||
|
||||
result.Add(row);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LogXnet.WriteLine($"StoredProcedure {storedProcedure} Error", LogXLabel.Exception);
|
||||
LogXnet.WriteLine(e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user