Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a DataTable using Entity Framework ExecuteStoreQuery

I am working with a system that has many stored procedures that need to be displayed. Creating entities for each of my objects is not practical.

Is it possible and how would I return a DataTable using ExecuteStoreQuery ?

public ObjectResult<DataTable> MethodName(string fileSetName) {
using (var dataContext = new DataContext(_connectionString))
{
var returnDataTable = ((IObjectContextAdapter)dataContext).ObjectContext.ExecuteStoreQuery<DataTable>("SP_NAME","SP_PARAM");
return returnDataTable;
}
like image 219
detroitpro Avatar asked Jan 03 '11 17:01

detroitpro


People also ask

How do I return a dataset in Entity Framework?

To get back the results in the form of a DataTable object in an application using Oracle database and Entity Framework EDMX, I needed to select data from unmapped shared views with an existing DB context instance.

What does ExecuteSqlRawAsync return?

The ExecuteSqlRawAsync() is another method to execute Stored Procedures and Raw SQL in Entity Framework Core asynchronously. But unlike FromSqlRaw() method, it returns the number of affected rows. Note that there is also another variant called ExecuteSqlRaw() which is of synchronous type.


1 Answers

Yes it's possible, but it should be used for just dynamic result-set or raw SQL.

public DataTable ExecuteStoreQuery(string commandText, params Object[] parameters)
{
    DataTable retVal = new DataTable();
    retVal = context.ExecuteStoreQuery<DataTable>(commandText, parameters).FirstOrDefault();
    return retVal;
}

Edit: It's better to use classical ADO.NET to get the data model rather than using Entity Framework because most probably you cannot use DataTable even if you can run the method: context.ExecuteStoreQuery<DataTable>(commandText, parameters).FirstOrDefault();

ADO.NET Example:

public DataSet GetResultReport(int questionId)
{
    DataSet retVal = new DataSet();
    EntityConnection entityConn = (EntityConnection)context.Connection;
    SqlConnection sqlConn = (SqlConnection)entityConn.StoreConnection;
    SqlCommand cmdReport = new SqlCommand([YourSpName], sqlConn);
    SqlDataAdapter daReport = new SqlDataAdapter(cmdReport);
    using (cmdReport)
    {
        SqlParameter questionIdPrm = new SqlParameter("QuestionId", questionId);
        cmdReport.CommandType = CommandType.StoredProcedure;
        cmdReport.Parameters.Add(questionIdPrm);
        daReport.Fill(retVal);
    }
    return retVal;
}
like image 190
chuck Avatar answered Oct 13 '22 05:10

chuck