Is it possible to return IEnumerable anonymous objects from a DataContext.ExecuteQuery?

I am developing a reporting engine in which reports are based on templates. Each template has a row with the SQL query, and each report has specific values ​​for the parameters of the SQL query. To make a report, I set parameters and called the DataContext.ExecuteQuery method to get a list of records. But in order to catch the returned columns, I have to know their names and have a class with the corresponding properties.

Is it possible to somehow return IEnumerable anonymous objects from DataContext.ExecuteQuery and then define their properties using Reflection?

I need the LINQ equivalent for SqlDataReader.GetValues .

Thanks!

+3
source share
3 answers

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.

+4
source

Yes you can do it. Look at this snippet.

 class Program { static void Main(string[] args) { var persons = new Person[]{ new Person{Age=22,Name="John Doe",Id=1}, new Person{Age=23,Name="Jack Smith", Id=2}, new Person{Age=34,Name="Sara Parker", Id=3} }; var anonData = GetAnonTypes(persons); foreach (var item in anonData as IEnumerable) { //use reflection to access propties } } static object GetAnonTypes(IEnumerable<Person> persons) { var query=from p in persons select new{ Id=p.Id, Name=p.Name }; return query; } } public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } 
0
source
  • The compiler cannot open your sql and determine the properties that must exist.
  • Since you want the compiler to do this, I have to conclude that you really do not understand anonymous input.

Do not use LinqToSql for this. Just use the DataReader method.

-4
source

Source: https://habr.com/ru/post/1340129/


All Articles