For simple data fetching scenario's, I tend to keep away from Entity Framework and go the micro-ORM approach using libraries like Dapper.
Today I had a small use case where I wanted to return some data using dynamic types in C# and handle it like a list of key-value pairs instead of using strongly typed objects. The good news is that this is supported out-of-the-box in Dapper.
Dapper gives you multiple overloads that returns a dynamic
type. Here is an example using Query()
:
public IList<Dynamic> GetTop10Products() | |
{ | |
string sql = "SELECT TOP 10 * FROM Products"; | |
using var connection = new SqlConnection(); | |
var products = connection.Query(sql); | |
return products; | |
} |
Simple but effective!
Remark: If you are not really looking for a dynamic result set but donāt want to create a class or record type, you can also use value tuples to map the returned rows:
string sql = "SELECT TOP 10 * FROM Products"; | |
using var connection = new SqlConnection(); | |
var products = connection.Query<(int ProductID, string ProductName)>(sql); | |
return products; |
More information
Dapper Anonymous Result - Learn How to Map Result to Dynamic Object (dappertutorial.net)