0

I am doing a repository call in EF, as soon as i access First or default i am getting null reference exception, could any body help with inputs?

  • is there any way to check if the Entity values are null? so that i can avoid Exception.

     public TEntity GetSingle(Func<TEntity, bool> where, params Expression<Func<TEntity, object>>[] navigationProperties)
    {
        TEntity item = null;
        using (var context = new CDREntities())
        {
            IQueryable<TEntity> dbQuery = context.Set<TEntity>();
    

    below line returns 56 entities with null values, because i dont have any entities in the table

            //Apply eager loading
            dbQuery = navigationProperties.Aggregate(dbQuery, (current, navigationProperty) => current.Include(navigationProperty));
    

    below is the place where i get null reference exception when i access above null entities, is there any thing wrong with the below statement?

            item = dbQuery
                .AsNoTracking() //Don't track any changes for the selected item
                .FirstOrDefault(where); //Apply where clause
        }
        return item;
    }
    

1 Answers1

0

Have you tried checking whether it is null or not

if(item == null) 
{
    // Handle null case
}

The query is simple, FirstOrDefault will return the first item in a db, or the first item in a collection of results, if there are no items in the table being queried, naturally there's nothing for EF to return.

EF handles such cases by returning null as it's appropriate. Simply check if the response is null, the only other way to avoid it is to have something in the database for it to return or performing a count operation against the table its self which is pointless if you are then going to have to query the table again for the data you just checked for it existing or not.

Also why are you creating a method called Single? The implementation of it is wrong for one, secondly the Single method exposed in Entity Framework behaves differently, it will throw an exception if more than 1 item matches the query.

Another point I'm wondering is why you're receiving 56 null items if your table is empty???

Aydin
  • 15,016
  • 4
  • 32
  • 42
  • IQueryable dbQuery = context.Set() - dbQuery is returning enumerable collection of entities in which each value is null, as there are no entries in db – user3016995 Apr 19 '18 at 18:05
  • i cannot check the item is null or not because the line item = dbQuery .AsNoTracking() //Don't track any changes for the selected item .FirstOrDefault(where); itself throwing exception – user3016995 Apr 19 '18 at 18:09