c# - LINQ 提示子查询返回多于 1 行

标签 c# linq

提取单个记录的简单代码(它是单个记录是因为主键是一个设置为自动编号的 int):

using (var db = new DataClasses1DataContext())
{
    var record = db.Projects.Single(x => x.ProjectID == projectID);
    record.Deleted = true;
    record.DeletedByUserID = MySession.Current.UserID;
    record.DeletedOn = DateTime.Now;
    db.SubmitChanges();
}

我不确定为什么,但在某些情况下,一旦它命中 db.SubmitChanges()我们得到一个异常说明 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

但是当我“观看”记录时,我只得到了一条记录。可能是什么原因造成的?

最佳答案

使用 db.Projects.First(x => x.ProjectID == projectID); 代替 Single 可能会有所帮助。

它甚至似乎是一个常见问题:http://social.msdn.microsoft.com/Forums/en-US/afb292ca-3a61-4a60-8e18-830b92489016/method-single-not-supported-by-linq-to-entities?forum=adodotnetentityframework

解决方法,不知道是否有帮助,但是来自上面的链接:

    public static TElement Single<TElement>
      (this IQueryable<TElement> query)
{
    if (query.Count() != 1)
    {
        throw new InvalidOperationException();
    }
    return query.First();
}



// Use it like this

Product prod = (from p in db.Product
                where p.ProductID == 711
                select p).Single();

关于c# - LINQ 提示子查询返回多于 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22870505/

相关文章:

c# - 使用 LINQ 包含 - 如何确保后面没有特定字符

c# - Linq 在单次迭代中选择和聚合

c# - 如何在 LINQ 中比较日期(Likewise Like 在 SQL 查询中)

c# - 在 richtextbox 中显示 stdout 和 stderr

c# - Asp.Net ViewState 性能

c# - 如果路径包含 "#",则 System.Uri 无法提供正确的 AbsolutePath 和 LocalPath

c# - 将 IQueryable 集合导出到 Excel

c# - 使用 linq 按具有空数据值的日期进行分组

c# - foreach 和方法组

c# - 使用 12c 客户端截断的存储过程 OUTPUT VARCHAR2 值