Map SQL Query results into entities (C#)

3.5k Views Asked by At

Is there a way to automap a query into a class in C# in order to strong type the query results? I don't want to access to query result with a DataTable, specifying manually the Column Name anymore.

4

There are 4 best solutions below

6
On BEST ANSWER

My favourite question. Use QueryFirst. Write your SQL in the SQL editor window, syntax validated as you type, then QueryFirst will generate the C# wrapper to execute it, with strongly typed inputs and outputs. And there are numerous other benefits :-) SqlServer, MySql and Postgres support built in. Others easy to add. Disclaimer : I wrote QueryFirst.

8
On

You should take a look at AutoMapper. It's an easy and user-friendly way to map a DataTable to a List<object> of your specification.

You can find an article which talks about it (including sample code) here.

If you want to automize the process, you can use dynamic objects which don't require you to create specific classes for every DataTable that you're using.

Hope this helped!

8
On

There is couple of options:

EntityFramework - powerful and heavyweight. https://msdn.microsoft.com/en-us/library/aa937723(v=vs.113).aspx

Dapper - lightweight - mostly mapper https://www.codeproject.com/Articles/212274/A-Look-at-Dapper-NET

If you need only mapping of stored procedures, queries etc, Dapper is good way to go, as it's basically adding extension methods to connection object. It cannot create database etc as Entity Framework but it all really depends on needs.

2
On

There is a helpful library on LINQ to DB

"LINQ to DB is the fastest LINQ database access library offering a simple, light, fast, and type-safe layer between your POCO objects and your database."

https://github.com/linq2db/linq2db