As long as we donβt have C # 4.0 with the keyword dynamic , we can use this solution (slightly modified code from the article Executing arbitrary queries in LINQ to SQL from Octavio HernΓ‘ndez Leal):
public static class DataContextExtension { public static IEnumerable<Dictionary<string, object>> ExecuteQuery(this DataContext dataContext, string query) { using (DbCommand command = dataContext.Connection.CreateCommand()) { command.CommandText = query; dataContext.Connection.Open(); using (DbDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) { while (reader.Read()) { Dictionary<string, object> dictionary = new Dictionary<string, object>(); for (int i = 0; i < reader.FieldCount; i++) dictionary.Add(reader.GetName(i), reader.GetValue(i)); yield return dictionary; } } } } }
This extension method returns IEnumerable from a dictionary of <> objects, where the keys are the names of the query columns.
source share