Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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


        }
    }
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading