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

后端 未结 4 1843
情话喂你
情话喂你 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.

提交回复
热议问题