using Microsoft.Data.SqlClient;
using System.Data;
using WebApplication1.Model;
namespace WebApplication1.RepositoryLayer
{
public class CRUDOperationRL:ICRUDOperationRL
{
private readonly IConfiguration configuration;
public CRUDOperationRL(IConfiguration _configuration)
{
this.configuration = _configuration;
}
public async Task<StudentResponse> InsertUpdateRecord(StudentRequest req)
{
StudentResponse obj = new StudentResponse();
try
{
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("@StudentId", req.studentId);
cmd.Parameters.AddWithValue("@StudentName", req.studentName);
cmd.Parameters.AddWithValue("@Email", req.emailId);
cmd.Parameters.AddWithValue("@DOB", req.dob);
cmd.Parameters.AddWithValue("@Gender", req.gender);
DataTable dt = await ExecuteProcedure(cmd, "USP_InsertUpdateStudentData");
if (dt != null && dt.Rows.Count > 0)
{
obj.status = "200";
obj.message = dt.Rows[0]["Result"].ToString();
}
}
catch (Exception ex)
{
obj.status = "500";
obj.message = ex.Message;
}
return obj;
}
public async Task<List<GetStudentData>> GetStudnetData(string studentId)
{
List<GetStudentData> res = new List<GetStudentData>();
try
{
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("@StudentId", studentId);
DataTable dt = await ExecuteProcedure(cmd, "USP_ShowStudentDetails");
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow rw in dt.Rows)
{
GetStudentData obj = new GetStudentData();
obj.studentId = Convert.ToInt32(rw["StudentID"]);
obj.studentName = Convert.ToString(rw["StudentName"]);
obj.emailId= Convert.ToString(rw["Email"]);
obj.dob = Convert.ToString(rw["DOB"]);
obj.gender = Convert.ToString(rw["Gender"]);
res.Add(obj);
}
}
}
catch (Exception ex)
{
throw new Exception();
}
return res;
}
public async Task<StudentResponse> DeleteStudentData(string studentId)
{
StudentResponse obj = new StudentResponse();
try
{
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("@StudentID", studentId);
DataTable dt = await ExecuteProcedure(cmd, "USP_Delete_StudentDetails");
if (dt != null && dt.Rows.Count > 0)
{
obj.status = "200";
obj.message = dt.Rows[0]["Result"].ToString();
}
}
catch (Exception ex)
{
obj.status = "500";
obj.message = ex.Message;
}
return obj;
}
public async Task<DataTable> ExecuteProcedure(SqlCommand cmd, string ProcedureName)
{
try
{
string connectionString = configuration.GetConnectionString("DBString");
using (SqlConnection con = new SqlConnection(connectionString))
{
DataTable dt = new DataTable();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = ProcedureName;
SqlDataAdapter dr = new SqlDataAdapter(cmd);
dr.Fill(dt);
return dt;
}
}
catch (Exception ex)
{
throw;
}
}
}
}
Surya Prakash (Admin) Reply
Thank Pratima !!