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

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

提交回复
热议问题