Home > Blockchain >  Querying with linq for a non-existent record says System.NullReferenceException
Querying with linq for a non-existent record says System.NullReferenceException

Time:01-02

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?

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

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;
        }


        }
    }
}

CodePudding user response:

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()"). 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.

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).

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.

CodePudding user response:

.FirstOrDefault(); will return null if no records are found

  • Related