2

我有一种方法来计算项目,但遇到了一个愚蠢的例外:

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

另外,还有一条线索,我的桌子是空的。根本没有行。如何处理这种情况。我也尝试过 Where 子句。见下文:

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

4 回答 4

1

FavouriteCompanies 为空。你可以这样做:

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

在那个解决方案if (result>0)中是多余的。

于 2012-04-30T10:27:23.853 回答
1

好吧,如果您可以包含堆栈,这会有所帮助,但我认为 FavouriteCompanies 集合中有一个 null (或者 _context 变量可能为 null - 如果您将许多方法与“。”链接在一起,您会遇到火车残骸很难说什么是空的)。您可以通过删除空值来防御性地解决这个问题:

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.

于 2012-04-30T10:27:28.517 回答
1

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.

于 2012-04-30T10:33:13.387 回答
1

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);
于 2014-11-19T07:46:55.090 回答