jeudi 19 octobre 2017

LINQ to SQL Reflection in Select

I've got the following problem. I have table in a SQL database which looks like this:

| id | attr0 | attr1 | attr2 | attr3 | attr4 | attr5 |

So, I want to get the data from this table in a for loop.

I've created the class

public class Attribute{
    public int Id {get; set;}
    public string Description {get; set}
}

And now i want to get all the attributes from table into one list

List<Attribute> attributeList = new List<Attribute>();
for(int i=0; i<6;i++)
{
    attributeList.Add((from a in db.Attributes
                  select new Attribute{
                      Id = a.Id,
                      Description = a.attr0}).First(); //How to use here i instead a fixed column name?
}

Is it possible to use i and get all attributes with one loop?

I was trying to use reflection but the compiler gives me an error, the code for that was:

for(int i=0; i<6;i++)
{
    attributeList.Add((from a in db.Attributes
                  select new Attribute{
                      Id = a.Id,
                      Description = a.GetType().GetProperty("attr"+i).GetValue(a,null))}).First();

UPDATE: The error is:

LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object, System.Object[])' method, and this method cannot be translated into a store expression.





Aucun commentaire:

Enregistrer un commentaire