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

后端 未结 4 1792
情话喂你
情话喂你 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:54

    Note that both SingleOrDefault() and FirstOrDefault() will not allow you to specify the default value.

    There's DefaultIfEmpty(), which allows you to specify the default value you want returned if there are no items in the enumerable. You can combine this one with First() (as in DefaultIfEmpty().First()) to achieve FirstOrDefault()-like behavior and a lambda to wrap creating a new instance and adding it to the set.

    If you just need to check for the existence of a record, you can also use Any(). However, this will result in two queries, if you need to process the record if it exists.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-20 04:58
    var efCompany = _dbRiv.Company
                      .SingleOrDefault(a => a.CompanyId == companyFeedInfo.CompanyId);
    
    if (efCompany != null)
    {
        // Use it
    }
    else
    {
        // Report to user, or whatever
    }
    
    0 讨论(0)
  • 2021-02-20 05:02

    You can also use

    _dbRiv.Company.find(#id) 
    

    if you are looking for a record without its included models.

    Or

    _dbRiv.Company.FirstOrDefault(x => x.Id == #id);
    

    I recommend FirstOrDefault over SingleOrDefault because of the performance. With SingleOrDefault it needs to scan the entire table and make sure there is only one record with the Id. With FirstOrDefault it can simply go until it finds that id then stop. On a large table it will save you small amounts of time with each query.

    Also you can use AsNoTracking to improve memory consumption if you don't need to track any changes made to the model. For instance if you are returning it via a rest request without calling save.

    0 讨论(0)
提交回复
热议问题