Using Entity Framework ExecuteStoreQuery to return a DataTable

code-first ef-code-first entity-framework stored-procedures

Question

I'm working with a system that needs to show a lot of stored processes. It is not realistic to create entities for each of my things.

Is it feasible, and if so, how would I do it?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;
}
1
16
11/5/2013 7:07:28 PM

Accepted Answer

No, I don't believe it will work. Entity Framework is designed to return entities, not zzz.DataTable objects.

If requiredDataTable Use pure ADO.NET in instead of objects.

11
1/3/2011 5:45:59 PM

Popular Answer

It is conceivable, but it should only be used for raw SQL or dynamic result sets.

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

Edit: Because you almost certainly won't be able to utilize Entity Framework, it's preferable to use traditional ADO.NET to get the data model.DataTable even if the method can be executed:context.ExecuteStoreQuery<DataTable>(commandText, parameters).FirstOrDefault();

ADO.NET Case Study

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;
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow