Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 select a;

To get a single record, when I know I am using the PK to retrieve it, I use something like:

var efCompany = (from a in _dbRiv.Company where a.CompanyId == companyFeedInfo.CompanyId select a).First();

Now, using the single record approach, if the PK is a faulty value (like it purposefully is in testing) the 2nd line throws an error.

What is the best practice way of getting a single record and dealing with it?

like image 939
Keith Barrows Avatar asked Jan 26 '10 20:01

Keith Barrows


People also ask

How do I select a single column in Entity Framework?

Select Top (1) UserId, Name from MyTable where UserId = 1; For multiple items you can simply chain Select after Where: var names = dbContext. MyTable.

What does AsNoTracking do in Entity Framework?

AsNoTracking(IQueryable)Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object.

How do you get entities back from a query without getting tracked by the context?

No-Tracking query using AsNoTracking() extention method The AsNoTracking() extension method returns a new query and returned entities do not track by the context. It means that EF does not perform any additional task to store the retrieve entities for tracking.

What does EF's DbContext need to be tracking in order to delete a row from the database?

The approach that you adopt to deleting entities via the DbContext depends on whether the context is currently tracking the entity being deleted or not. In the following example, the entity to be deleted is obtained by the context, so the context begins tracking it immediately.


1 Answers

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.

like image 68
Jon Skeet Avatar answered Oct 21 '22 23:10

Jon Skeet