C# Select中LINQ到SQL的反射
我有以下问题。SQL数据库中的表如下所示: |id | attr0 | attr1 | attr2 | attr3 | attr4 | attr5| 所以,我想在for循环中从这个表中获取数据 我已经创建了这个类 现在我想把表中的所有属性都放到一个列表中 更新: 错误是: LINQ to Entities无法识别方法“System.Object GetValue(System.Object,System.Object[])”方法,并且无法将此方法转换为存储表达式C# Select中LINQ到SQL的反射,c#,.net,linq,reflection,C#,.net,Linq,Reflection,我有以下问题。SQL数据库中的表如下所示: |id | attr0 | attr1 | attr2 | attr3 | attr4 | attr5| 所以,我想在for循环中从这个表中获取数据 我已经创建了这个类 现在我想把表中的所有属性都放到一个列表中 更新: 错误是: LINQ to Entities无法识别方法“System.Object GetValue(System.Object,System.Object[])”方法,并且无法将此方法转换为存储表达式 您试图在“数据库”级别使用反
您试图在“数据库”级别使用反射,而LinqToEntity无法将其转换为sql 如果可能的话,这将导致对同一行运行查询6次 尝试先实例化db row类,然后在该对象上使用反射
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)
});
}
List attributeList=newlist();
DbAttribute attrist=db.attributes.First();
对于(int i=0;i<6;i++)
{
attributeList.Add(新属性{
Id=attrFirst.Id,
Description=(字符串)attrFirst.GetType().GetProperty(“attr”+i).GetValue(attrFirst)
});
}
无法将GetValue
转换为t-SQL,Linq to实体无法识别它。您可以查看此答案以了解更多详细信息
试试这个解决方案。这将为您提供您想要的:
var first = (from a in db.Attributes select a).FirstOrDefault();
List<Attribute> t = first?.GetType().GetProperties()
.Select(c => new Attribute { Id = first.Id , Description = c.GetValue(first).ToString()})
.ToList();
var first=(从db.Attributes中的a中选择a).FirstOrDefault();
List t=first?.GetType().GetProperties()
.Select(c=>new属性{Id=first.Id,Description=c.GetValue(first.ToString()})
.ToList();
使用这种方法,任何进一步的操作都是使用Linq to对象对内存中已经存在的数据执行的,并且您不会再收到此错误。同样,通过使用LINQ,您不再需要来执行循环。由于列名以小写a开始,因此GetProperty(“Attr”+i)
应该是GetProperty(“Attr”+i)
(小写a
)。我不知道这是否是错误,但它看起来可疑。我认为应用程序设计应该支持它的逻辑。您的逻辑需要属性的迭代-所以请将其保存在数据库中,这样迭代将是最容易和最有效的。@Twometer很好的捕获。然而,OP谈论的是“编译器”错误,而您提到的可能是运行时错误。问题可能是因为它是linq语句的一部分,无法转换为db查询。首先获取所有属性,然后对ResultTextCellent进行反射!这对我来说是我想要的!非常感谢。
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();
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)
});
}
var first = (from a in db.Attributes select a).FirstOrDefault();
List<Attribute> t = first?.GetType().GetProperties()
.Select(c => new Attribute { Id = first.Id , Description = c.GetValue(first).ToString()})
.ToList();