samedi 29 octobre 2022

Function returns empty objects but right before the return object is populated [duplicate]

I tried to make a function that will return any type of DTO from a stored procedure with EF CORE 6. My approach:

  • got a DataTable
  • used reflection to map the DataTable to a generic T

DTO

    public class JobsDTO
    {
        public string Luna;
        public int NrSaptamana;
        public string ServiciuPrestat;
        public bool IsServiciuPrestat;
    }

This is the function that does it and it works as expected. It populates a List with data

public async Task<List<T>> ExecuteProc<T>() where T : new()
        {
            DataTable dataTable = new DataTable();
            var connection = databaseContext.Database.GetDbConnection();
            var dbFactory = DbProviderFactories.GetFactory(connection);

            using(var cmd = dbFactory!.CreateCommand())
            {
                cmd.Connection = connection;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "GetJob";

                using(var adapter = dbFactory.CreateDataAdapter())
                {
                    adapter.SelectCommand = cmd;
                    adapter.Fill(dataTable);
                }
            }
            List<T> list = new List<T>();

            FieldInfo[] fields = typeof(JobsDTO).GetFields();

            foreach (DataRow dr in dataTable.Rows)
            {
                T t = new T();
                foreach (FieldInfo fi in fields)
                    fi.SetValueDirect(__makeref(t), dr[fi.Name]);

                list.Add(t);
            }
                
            return list;
        }

The enpoint

[HttpGet("getJobs")]
        public async Task<IActionResult> GetJobs()
        {
            try
            {
                var res = await unitOfWork.ExecuteProc<JobsDTO>();
               
                return Ok(res);  *HERE I TOOK THE PRINTSCREEN*
            }
            catch(Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

Please look at the values of res right before returning Ok(res) Data before reutrn And here is the result that arrives in swagger Data after return

I assumed it has something to do with the object reference so I copied by value an object from list and returned the copy insted but the result was the same.

If anyone has a different approach in getting DTOs from stored procedures with ef core 6 please let me know





Aucun commentaire:

Enregistrer un commentaire