Entity Framework returns any type of data with Sqlquery

Asked

Viewed 137 times

3

I’m trying to return dynamic values of a query also dynamic, but I can’t figure out how to get any kind of data from the database.

Here’s what I’m trying to do

comandoSql = @" SELECT " + NomeCampo + " FROM " + Tabela + " WHERE Id = @p0";
var result = _db.Database.SqlQuery<string>(comandoSql, id).ToList();

It works when my return is a varchar field. However as the query is dynamic, I may want to query other fields of other tables, so if a Numeric, datetime etc comes back an error.

I have tried using Sqlquery and Sqlquery but cannot get the value from inside the object after.

  • Have you tried using Dapper? It will do exactly what you want and is much lighter than EF.

  • with Dapper I can, but for this solution I can’t use Dapper for some internal issues.

  • Why not try using the EF context? You call the context class of the database and create objects that give access to the table. This would solve?

  • Use the dynamic doesn’t solve? _db.Database.SqlQuery<dynamic>(comandoSql, id); Then I’d just have to process the information he returns.

  • so I tried using Dynamic, but I can’t handle the information when it returns. The information value is like {Object} only.

  • But of that object can’t get the guy out? object.GetType()?

  • I can’t do anything with that object. it has no function or property after it returns.

  • 1

    Solved by Dapper even using Dynamic return.

Show 3 more comments

1 answer

3

Why not use a generic list (untested code)?

public static List<T> GetQuery<T>(string NomeCampo, string Tabela, int id) where T : class
{
    comandoSql = $" SELECT {NomeCampo} FROM {Tabela} WHERE Id = @p0";
    return _db.Database.SqlQuery<T>(comandoSql, id).ToList();
}

The use would be:

List<string> lista = GetQuery<string>("Nome", "Clientes", 10);
  • thanks for the reply. but falls in the same case that had explained. i need to pass the data type for this method to work, the problem is that I don’t have the data type that will come from each field passed in the query.

  • Not having this information becomes difficult! There is no way to know the type?

  • this is what I wanted to know. if there is a way to get the field independent of type. but I did with Dapper same, with Dynamic type.

Browser other questions tagged

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