LINQ的返回列表或单个对象对象、列表、LINQ

2023-09-09 21:01:00 作者:;亱晚収納機

我有一个LINQ到实体查询像这样的:

I have a Linq to Entities query like this one:

var results = from r in entities.MachineRevision
              where r.Machine.IdMachine == pIdMachine
                 && r.Category == (int)pCategory
              select r;

通常情况下,我用下面的code,以检查是否存在返回结果:

Usually, I use the code below to check if some results are returned:

if (results.Count() > 0)
{
    return new oMachineRevision(results.First().IdMachineRevision);
}

不过,我收到的 NotSupportedException异常在如果的条件。

该错误信息是:无法创建类型闭合式的恒定值。只有原始类型('如的Int32,字符串和GUID')在这方面的支持。的

注意 pCategory 是一个枚举类型。

推荐答案

修改:根据您的更新,错误可能会在你的实体类与枚举。看到这个博客条目了解更多信息和解决方法。我要离开我原来的答案,在你的查询语法的改善。

EDIT: Based on your update, the error may be related to an enum in your entity class. See this blog entry for more information and a work-around. I'm leaving my original answer as an improvement on your query syntax.

尝试自己用FirstOrDefault,然后检查如果结果是空做第一个实体的选择查询。

Try doing the selection of the first entity in the query itself using FirstOrDefault and then check if the result is null.

int compareCategory = (int)pCategory; // just a guess
var result = (from r in entities.MachineRevision
              where r.Machine.IdMachine == pIdMachine
                 && r.Category == compareCategory
              select r).FirstOrDefault();

if (result != null)
{
     return new oMachineRevision(result.IdMachineRevision);
}