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?
Select Top (1) UserId, Name from MyTable where UserId = 1; For multiple items you can simply chain Select after Where: var names = dbContext. MyTable.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With