LINQ查询问题,序列不包含元素 [英] LINQ Query Issue, Sequence contains no elements

查看:164
本文介绍了LINQ查询问题,序列不包含元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新表中的单个记录,但是当我运行 .Firstordefault()时,我收到错误:对象引用未设置为对象的实例,如果使用 .First(),我得到序列不包含元素。

I'm trying to update a single record in a table, but when I run .Firstordefault(), I get the error: "Object reference not set to an instance of an object.", and if use it with .First(), I get "Sequence contains no elements".

使用它的另一个地方,它的工作正常,但这次造成错误。

Using it another place, its working fine, but this time its causing errors.

这里是代码:

public class AllownceDetails
{
  public int ta_id{get;set;}
  public int tvrid{get;set;}
  public DateTime ofDate{get;set;}
  public string status{get;set;}
  public string userid {get;set;}
}
//Update Method
public void Update(AllownceDetails Allowncedtl)
    {

        var ta = (from a in ce.tbl_tvrallownce
                  where a.tvrid == Allowncedtl.tvrid 
                   //error: Sequence contains no elements

                  select a).SingleOrDefault();

        ta.status = Allowncedtl.status; 
                   //error:Object reference not set to an instance of an object
        ce.SaveChanges();


    }


推荐答案

p>查询不能返回任何数据。在SQL数据库上运行分析器以查看正在执行的物理查询,并尝试针对数据库手动执行它,以查看数据的外观。您可能需要调整查询(或数据)以获取您要查找的结果。

The query must not be returning any data. Run a profiler on the SQL database to see the physical query being executed and try to execute it manually against the database to see what the data looks like. You probably have to adjust the query (or the data) to get the results you're looking for.

序列不包含元素基本上是LINQ的方式告诉您你试图从列表中引用一个没有任何东西的元素。所以调用诸如 .First() .Single()的东西找不到任何东西,因此这个错误。

"Sequence contains no elements" is basically LINQ's way of telling you that you're trying to reference an element from a list that doesn't have anything. So calls to things like .First() or .Single() can't find anything, hence the error.

将呼叫更改为 .FirstOrDefault() .SingleOrDefault )然后它将与该类型的默认值一起使用,对于引用类型,默认值为 null 。所以如果你设置一些东西到 null 然后尝试调用一个方法,你会得到对象引用没有设置为对象的一个​​实例

When you change the calls to something like .FirstOrDefault() or .SingleOrDefault() then it will go with "default" value for that type, and for reference types the default is null. So if you set something to null and then try to call a method on it, you'll get object reference not set to an instance of an object.

这篇关于LINQ查询问题,序列不包含元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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