c# - Select 中的 LINQ to SQL 反射

标签 c# .net linq reflection

我遇到了以下问题。我在 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/

相关文章:

c# - 如何: Write a thread-safe method that may only be called once?

c# 语法快捷方式在连续多次引用对象名称时跳过它

.net - VB.NET - 给定一个日期,如何获取下一个星期五的日期?

C# 使用 LINQ 解析简单的 XML 文件

c# - 是否有一种 LINQ 方法可以执行类似 foreach 的操作然后调用函数?

c# - 无法安装 NuGet 包

c# - 从 Asp.Net MVC View 转到下一条记录

.net - Visual Studio 2008/2010 : show method names in Find In Files results

c# - 将 int 转换为 short 的更好方法? (如果不可能则为 NULL)

c# - 具有动态 groupBy 的动态对象列表