我遇到了以下问题。我在 SQL 数据库中有一个表,如下所示:
|编号 |属性0 |属性1 |属性2 |属性3 |属性4 |属性5 |
所以,我想在 for 循环中从这个表中获取数据。
我已经创建了类
public class Attribute{
public int Id {get; set;}
public string Description {get; set}
}
现在我想把表中的所有属性放到一个列表中
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?
}
是否可以使用 i
并通过一个循环获取所有属性?
我试图使用反射,但编译器给了我一个错误,错误代码是:
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();
更新: 错误是:
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.
最佳答案
您正在尝试在“数据库”级别上使用反射,而 LinqToEntities 无法将其转换为 sql。
如果可以的话,将导致对同一行运行查询 6 次。
首先尝试实例化您的数据库行类,然后对该对象使用反射
List<Attribute> attributeList = new List<Attribute>();
DbAttribute attrFirst = db.attributes.First();
for (int i = 0; i < 6; i++)
{
attributeList.Add(new Attribute {
Id = attrFirst.Id,
Description =(string)attrFirst.GetType().GetProperty("attr" + i).GetValue(attrFirst)
});
}
关于c# - Select 中的 LINQ to SQL 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46824423/