LINQ的返回列表或单个对象 [英] Linq returns list or single object

查看:194
本文介绍了LINQ的返回列表或单个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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);
}

这篇关于LINQ的返回列表或单个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆