Search code examples
entity-frameworkenumerabledatabase-first

Tricks to generate List<double> in entity framework as data from similar set of columns


I am developing an silverlight application using WCF and EF.

I am using Database first as our database already exists.

I have a table that consists of 100 columns with datatype real. We want to generate a class which has a List<double> or List<float> instead of that 100 discrete variables in the class for each column.

Is this possible ?? Can someone give me an example?


Solution

  • There's no direct way. What you have to do is use reflection to convert it into a List<double>. Suppose your table names is called MyObject, then EF will generate a class MyObject to represent a row in that table. You can then do:

    Type type = typeof(MyObject);
    // Get properties (columns) through reflection 
    PropertyInfo[] properties = type.GetProperties(); 
    List<List<double>> allRows = new List<List<double>>();
    
    using(var dbContext = MyDB.GetContext())
    {
        foreach(var row in dbContext.MyRows)
        {
             List<double> columnValues = new List<double>();
             foreach (PropertyInfo property in properties)
             {
                // The sql type REAL will map to either float or double
                if(property.PropertyType == typeof(float)) 
                {
                     columnValues.Add( (double) property.GetValue(row, null) );
                }
             }
             allRows.Add(columnValues);
        }
    }
    

    Hope you get the idea.