2009-05-14 8 views
3

レポートをテンプレートに基づいて作成するレポートエンジンを開発します。すべてのテンプレートにはSQL問合せの文字列があり、すべてのレポートにはSQL問合せパラメータの特定の値があります。レポートをレンダリングするには、パラメータを設定し、DataContext.ExecuteQueryメソッドを呼び出してレコードのリストを取得します。しかし、返された列をキャッチするには、名前を知っていて、対応するプロパティを持つクラスが必要です。DataContext.ExecuteQueryから匿名オブジェクトのIEnumerableを返すことはできますか?

何らかの理由で、匿名オブジェクトのIEnumerableをDataContext.ExecuteQueryから返し、Reflectionを使用してそのプロパティを確認できますか?

私はSqlDataReader.GetValuesのLINQ相当物が必要です。

ありがとうございます!

答えて

4

我々は、この溶液(オクタビオエルナンデスレアルによる論文Executing arbitrary queries in LINQ to SQLからわずかに修正されたコード)を使用することができdynamiсキーワードとC#4.0になるまでこの拡張メソッド辞書<のIEnumerableをを返し

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; 
       } 
      } 
     } 
    } 
} 

>オブジェクトキーはクエリ列の名前です。

0

はい、できます。 このスニペットをご覧ください。

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

残念ながら、これは役に立ちません。私はDataContext.ExecuteQueryからいくつかの型をパラメータとして欲しいIEnumerableの匿名オブジェクトが必要です。 –

-4
  • コンパイラは、SQLを開き、存在するはずの特性を決定することはできません。
  • コンパイラがそれを行うことを望むので、私はあなたが本当に匿名の型を理解していないと結論づけなければなりません。

これにはLinqToSqlを使用しないでください。 DataReaderメソッドを使用します。

関連する問題