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;
}
No, I don't think that'll work - Entity Framework is geared towards returning entities and isn't meant to return
DataTable
objects.If you need
DataTable
objects, use straight ADO.NET instead.Yes it can easily be done like this:
This method uses the connection string from the entity framework to establish an ADO.NET connection, to a MySQL database in this example.
Yes it's possible, but it should be used for just dynamic result-set or raw SQL.
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:
By the rule, you shouldn't use a DataSet inside a EF application. But, if you really need to (for instance, to feed a report), that solution should work (it's EF 6 code):
In my Entity Framework based solution I need to replace one of my Linq queries with sql - for efficiency reasons. Also I want my results in a
DataTable
from one stored procedure so that I could create a table value parameter to pass into a second stored procedure. So:I'm using sql
I don't want a
DataSet
Iterating an
IEnumerable
probably isn't going to cut it - for efficiency reasonsAlso, I am using EF6, so I would prefer
DbContext.SqlQuery
overObjectContext.ExecuteStoreQuery
as the original poster requested.However, I found that this just didn't work:
_Context.Database.SqlQuery<DataTable>(sql, parameters).FirstOrDefault();
This is my solution. It returns a
DataTable
that is fetched using an ADO.NETSqlDataReader
- which I believe is faster than aSqlDataAdapter
on read-only data. It doesn't strictly answer the question because it uses ADO.Net, but it shows how to do that after getting a hold of the connection from theDbContext