Return data from a query without certain fields

Asked

Viewed 56 times

-1

Good morning, I made a query that returns only completed data between a given period, I only need these two data but entityframework is demanding some fields that I do not need as ID. Is there any way to ignore this data and only return to my query?

Code:

try
        {
            var year = DateTime.Now.ToString("yyyy");
            var dataInicial = year + "-01-01";
            var dataFinal = year + "-12-31";

            string sql = "";
            sql += " SELECT distinct Concluido Concluidos, count(Concluido) Total" +
                " WHERE DataInicio BETWEEN " + "'" + dataInicial + "' AND " + "'" + dataFinal + "' group by concluido;";

            
            var p = await context.Projetos
                     .FromSqlRaw(sql)
                     .AsNoTracking()
                     .ToListAsync();
            return Ok(p);
        }
        catch (System.Exception ex)
        {
            return this.StatusCode(StatusCodes.Status500InternalServerError, "Falha: " + ex.ToString());
        }

None of the fields returns in the query exists in the table, wanted to return the same data as the query:

inserir a descrição da imagem aqui

1 answer

0


I found a code posted on stackoverflow but posted directly on the site Entity framework core that can help you with what you need!

https://entityframeworkcore.com/knowledge-base/51678809/can-entity-framework-core-run-sqlquery-

It indicates that maybe Voce can execute a query through component commands and wrote a function that can be coupled to its code.

public static List<T> RawSqlQuery<T>(string query, Func<DbDataReader, T> map)
{
    using (var context = new DbContext(new DbContextOptionsBuilder().Options)
    {
        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;
            }
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.