Search code examples
c#entity-frameworkentity-framework-4ado.net

Execute custom SQL with Entity Framework?


I need to execute a custom query which will be saved somewhere in the database, and I need it to return in a DataTable, or DataSet and bind it to a GridView which will have autogenerate columns set to true.

All my Data Access Layer works perfectly with Entity Framework, but for some specific scenario I need to do this, and I wonder if I should combine ADO.NET with Entity Framework, or if EF can do it somehow.


Solution

  • If your goal is to return ADO.NET structures (DataTable or DataSet), then just use classic ADO.NET. You'll find it easier than trying to bind data to an Entity set and then populating a DataTable or DataSet yourself.

    However, if you're really and truly interested running a custom query through EntityFramework, take a look at ExecuteQuery. It allows you to execute a SQL Query and maps the result back to entities in your model. It would then be an exercise on your part to take the IEnumerable result and map it to a DataTable or DataSet. Hence my original answer of "just do it with good ol' fashioned ADO.NET methods."