Entity Framework - Correct way to check for single records before using them

后端 未结 4 1793
情话喂你
情话喂你 2021-02-20 04:11

To get a LIST of records I normally do something along the lines of:

var efCompany = from a in _dbRiv.Company where a.CompanyId == companyFeedInfo.CompanyId sele         


        
4条回答
  •  故里飘歌
    2021-02-20 04:56

    Use SingleOrDefault if you expect 0 or 1, or FirstOrDefault if you just need the first record out of potentially many, but can cope with 0. Both will return the default value for the type (usually null) if there are no results.

    By the way, queries like this are generally more readable (IMO) without using a query expression, so you might have something like:

    var efCompany = _dbRiv.Company
                          .Where(a => a.CompanyId == companyFeedInfo.CompanyId)
                          .SingleOrDefault();
    
    if (efCompany != null)
    {
        // Use it
    }
    else
    {
        // Report to user, or whatever
    }
    

    Query expressions are great when you're using multiple operators, or doing relatively complex things like joins - but if you've just got a where clause or just got a projection, this "dot notation" is simpler IMO. It also works better when you need to call a method like FirstOrDefault at the end.

提交回复
热议问题