简体   繁体   English

使用 linq 查询不存在的记录说 System.NullReferenceException

[英]Querying with linq for a non-existent record says System.NullReferenceException

Querying my sql table with linq for a record that I know doesn't exist I get the following error System.NullReferenceException: 'Object reference not set to an instance of an object, but.FirstOrDefault() is not supposed to handle it if it doesn't find nothing in database, put the default values?使用 linq 查询我的 sql 表以获取我知道不存在的记录我收到以下错误在数据库中找不到任何内容,请输入默认值?

What I want to do is that if a record does not exist in my database, give a message to the user indicated this, but if the record exists, I want it to bring information我想做的是,如果我的数据库中不存在记录,则向用户发送一条消息以表明这一点,但如果记录存在,我希望它带来信息

I created an example so as not to attach all my code and express my failure我创建了一个示例,以免附加我的所有代码并表达我的失败

Code of my main form我的主要形式的代码

namespace Fallas
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void numerofactura_Leave(object sender, EventArgs e)
        {
            var bill = Bill.billfromid (billnumber.Text);
            numerofactura.Text = bill.Numero;
            nombrecliente.Text = bill.Cliente;

        }

Code of my class我的密码class

namespace Fallas
{

   public class BillModel
    {
        public string Number { get; set; } 
        public string Customer { get; set; }    
        public decimal Subtotal { get; set; }
        public decimal Total { get; set; }  
    }
    public static class Bill
    {
        public static BillModel billfromid(string number) 
    {
        using AppDatabase db = new AppDatabase();
        {
            Bill fct= (from u in db.vta_factura
                                where u.Numero == number
                       select u).FirstOrDefault();
            if (fct.Factura_ID == 0)
            {
                MessageBox.Show("Bill not found!", "Atencion!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return new Bill();
            }
            return fct;
        }


        }
    }
}

Start from this line:从这一行开始:

Bill fct= (from u in db.vta_factura
           where u.Numero == number
           select u).FirstOrDefault();

When the line ends, if no matching record exists the fct variable will be set to null (the default value for any class, as per the "or default" part of " .FirstOrDefault() ").当该行结束时,如果不存在匹配记录,则fct变量将设置为null (任何 class 的默认值,根据“ .FirstOrDefault() ”的“或默认”部分)。 Then on the next line we have this:然后在下一行我们有这个:

if (fct.Factura_ID == 0)

You can't look up the Factura_ID property (or any other property) on a null variable, and so we get the NullReferenceException.您无法在null变量上查找Factura_ID属性(或任何其他属性),因此我们得到 NullReferenceException。

You probably want to do this instead:你可能想这样做:

if (fct is object)

Or this:或这个:

if (fct != null)

is object is a relatively recent pattern for checking null in modern C#. It's supposed to be efficient, helps simplify code for some edge cases around nullable/value types, and expresses it in a positive way (no negation). is object是一个相对较新的模式,用于在现代 C# 中检查 null。它应该是高效的,有助于简化一些围绕可空/值类型的边缘情况的代码,并以积极的方式表达它(没有否定)。

Alternatively, you could just return the result from this method, with no check, and let higher-level calling code decide on the best way to respond.或者,您可以只返回此方法的结果,不进行检查,让更高级别的调用代码决定最佳响应方式。 Then the method could also be useful in a context where a MessageBox is not appropriate.那么该方法在 MessageBox 不合适的上下文中也很有用。

.FirstOrDefault(); will return null if no records are found如果没有找到记录,将返回 null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM