【问题标题】:Linq query to return booleanLinq 查询返回布尔值
【发布时间】:2013-06-05 15:56:42
【问题描述】:

我正在使用 .AddObject() 将数据插入到我的实体表中。该对象是实体表的类型。对象是 eventStudent,它有字符串 eventStudent.ID、bool eventStudent.StudentPresent、bool eventStudent.ParentPresent。

学生是包含学生 ID 的字符串列表。他们在活动中的存在是在另一个称为参加者的对象中,由 String studentID、bool studentPresent 和 bool parentPresent 组成。只有 StudentPresent 和/或 ParentPresent 为 true 的学生 ID 才会出现在与会者列表中。 当我加载我的 eventStudent 对象时,我需要设置 StudentPresent 和 ParentPresent。这是我想出的:

foreach (StudentMinimum student in students)
{
eventStudent.StudentPresent = (from a in attendees
                           where a.StudentID.Contains(student.StudentID)
                           && a.StudentPresent
                           select a.StudentPresent);
}

我收到错误无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“bool”

如何改进我的查询,以便将 eventStudent.StudentPresent 设置为 True 或 False?

【问题讨论】:

  • 尝试将 .FirstOrDefault() 放在查询的末尾?
  • 宾果游戏!谢谢你。
  • 酷,我会发布一个正确的答案,如果你愿意接受,将不胜感激。

标签: c#-4.0 entity-framework-4 asp.net-4.5


【解决方案1】:

编译器不知道您的查询将返回什么类型,因为您没有将它显式转换为类型。结果,它获得了一个通用的 IEnumerable 类型(可能返回很多记录,对吗?因此是 IEnumerable。这些记录都可以是任何类型,因此是通用类型)。

因此,如果您的数据库中的数据不正确并且您返回了多条记录,则转换:

StudentPresent
true
false
false

到布尔值不会发生。有几种方法可以解决这个问题。就个人而言,我会做类似的事情

var studentPresent = (from a in attendees
                           where a.StudentID.Contains(student.StudentID)
                           && a.StudentPresent
                           select a.StudentPresent).FirstOrDefault();

eventStudent.StudentPresent = (bool)studentPresent;

嗯,实际上,我会使用 lambda 查询,但这只是个人喜好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多