user240141
user240141

Reputation:

Null reference exception while using Count

I have a method to get count of the items, but got stucked with a silly exception:

 internal static bool IsCompanyInList(int companyId, int favoritecompanyId)
        {
            var result = _context.FavouriteCompanies.Count(c => c.CompanyId == companyId && c.FavouriteCompanyId == favoritecompanyId); // getting exception here
            if ( result >0)
                return true;
            return false;
        }

Also, one more clue, my table is empty . There is no row at all. How to handle this situation. I have also tried Where clause. See below:

 var result = _context.FavouriteCompanies.Where(criteria_here);

Upvotes: 2

Views: 5076

Answers (4)

Youngjae
Youngjae

Reputation: 25080

For me, one of string (or nullable column) value was null.

        var result = _context.FavouriteCompanies.Count(c => c.CompanyId != null && c.CompanyId == companyId && c.FavouriteCompanyId != null && c.FavouriteCompanyId == favoritecompanyId);

Upvotes: 1

Tormod
Tormod

Reputation: 4583

The error could be anywhere you attempt to access a member.

var result = _context.FavouriteCompanies.Count(c => c.CompanyId == companyId && c.FavouriteCompanyId == favoritecompanyId);

is _context null? is _context.FavoriteCompanies null? does FavoriteCompanies contain a record in which CompanyId or FavouriteCompanyId is null?

Since this is Linq2Sql, you can ask c.FavouriteCompanyId.Isnull() within the count clause before accessing the member itself.

Upvotes: 1

Aidan
Aidan

Reputation: 4901

Well it would help if you could include the stack, but I presume that the FavouriteCompanies collection has a null in it (or perhaps the _context variable is null - if you chain lots of methods together with a "." you get a train-wreck where it is hard to tell what is null). You could get round this defensively by removing the nulls :

var result = _context.FavouriteCompanies.Where( c => c != null ).Count(...)

although to be honest it would be much better to find out where a null has been inserted into FavourieCompanies and stop it there.

Upvotes: 1

Kamil Będkowski
Kamil Będkowski

Reputation: 1092

FavouriteCompanies is null. You can do something like that:

internal static bool IsCompanyInList(int companyId, int favoritecompanyId)
            {
                var result = _context.FavouriteCompanies;
                if (result!=null)
                {
                    return result.Any(c => c.CompanyId == companyId && c.FavouriteCompanyId == favoritecompanyId);
                } 

                return false;
            }

In that solution if (result>0) is redundant.

Upvotes: 1

Related Questions