Search code examples
c#linq-to-entitiesentity-framework-6

C# EF6 issue binding Linq result to DataGridView where date column is null


All, I'm having an issue with the Linq query below:

private void BindDataGrid(string _filter)
{
    using (var context = new Kennels_Data_ModelContainer())
    {
        var grid = context.Pricings
            .Where(x => x.AnimalType.Type == _filter)
            .Select(x=> new {x.PriceStart, x.PriceEnd, x.Price});

        if (grid != null)
        {
            var results = grid.ToList();
            pricingDataGridView.DataSource = results;
            pricingDataGridView.Columns[0].Width = 80;
            pricingDataGridView.Columns[1].Width = 80;
            pricingDataGridView.Columns[2].Width = 57;
        }
    }
}

I'm using Visual Studio 2013 and Entity framework 6, with SQL Server 2012.

The query worked fine up until I changed the PriceEnd Column in my database to allow it to hold nulls, and I know that at least one row has a null value in it.

This code is held in a Windows Form and is called by the Load method of the form, to bind to pricingdataGridView.

The code throws System.NullReferenceException and Additional Information is Object reference not set to an instance of an object.

I've looked all over and I can find plenty of references to dealing with null in the where clause of the Linq query, but I an find nothing at all relating to handling null values in the returned set.

Any help is appreciated.

Cheers.


Solution

  • At first, has EF model been updated? NullReferenceException might be thrown if in your model PriceEnd field remained decimal, but should become decimal?

    LINQ null check, to avoid these records:

    ... context.Pricings.Where(x => x.AnimalType.Type == _filter && x.PriceEnd != null)...