Fakhar uz Zaman
Fakhar uz Zaman

Reputation: 299

Iterate through all columns of table in entity framework

I am working in ASP.Net MVC and using Entity Framework.

I have following table schema

MyTable(Y1947, Y1948, Y1949, Y1950,.........Y2012)

Columns start from Y1947 to Y2012.

I want to iterate through all of these columns. I am using following code, which is not executable:

    EntityFramework ef = new EntityFramework();
    var q = from table in ef.MyTable
            select table;

    int i = 1947;

    foreach(var item in q)
    {
       string str=item["Y" + i].toString();   // Error in Entity Framework
       i++;
    }

But Entity Framework restricts to use item.Y1947 etc, I just want to iterate through all columns. Please help me how to do this.

Upvotes: 1

Views: 8346

Answers (2)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

Not sure about what you wanna achieve, but if I understood well, I would go for something like that

public partial class MyTable {

  public string DisplayYValues() {
    var sb = new StringBuilder();
    var properties = this.GetType().GetProperties().Where(m => m.Name.StartsWith("Y"));

   foreach (var property in properties) {
      var value = property.GetValue(this, null);
      sb.AppendLine(value == null ? string.Empty : value.ToString());
   }
   return sb.ToString();
  }
}

then usage

EntityFramework ef=new EntityFramework();
    var q=(from table in ef.MyTable
           select table).ToList();

var result = q.Select(m => m.DisplayYValues());

Upvotes: 1

undefined
undefined

Reputation: 34248

In entity framework you dont get a data table you get an object. If you are really wanting a datatable or similar perhaps its best to pick another framework.

However you can do this with reflection, something of the form (haven't compiled this but you get the picture)

foreach(var item in q)
{
    foreach(var col in item.GetType().GetProperties().Where(p=>p.Name.StartsWith("Y19") || p.Name.StartsWith("Y20"))
    {
        var thing = col.GetValue(item, null);
    }
}

Upvotes: 4

Related Questions