.ToListAsync
is used to get a collection of items from DB in EF Core. That's clear. But what is the right way to get single item? In async way if possible.
public async static Task<Source> LoadEntityAsync(int sourceID)
{
using (var db = new RPDBContext())
{
var sources =
await
db.Source
.Where(x => x.SourceID == sourceID)
.ToListAsync();
// TODO that's like a hack:
return sources.First();
}
}
Entity Framework supports the following three methods to load related data. In Eager Loading, all relevant data for an entity is loaded at the time of the query of the entity in the context object. Eager Loading can be done by using the "Include" method. To perform Eager Loading, Lazy Loading must be disabled.
Entity Framework Core allows you to use the navigation properties in your model to load related entities. There are three common O/RM patterns used to load related data. Eager loading means that the related data is loaded from the database as part of the initial query.
Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.
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.
You should use SingleOrDefaultAsync
if you want the object to be unique.
If you know that the object is unique from domain restrictions or if you are accessing it through primary key then you can use FirstOrDefaultAsync
.
var sources = await db.Source
.Where(x => x.SourceID == sourceID)
.SingleOrDefaultAsync();
you can use another overload and shorten the query
var sources = await db.Source
.SingleOrDefaultAsync(x => x.SourceID == sourceID);
same rules apply to FirstOrDefaultAsync
.
If you want to ensure that the object exists just remove the OrDefault
part and use SingleAsync
and FirstAsync
.
If you need to retrieve a single item, use FirstOrDefaultAsync
:
public static Task<Source> LoadEntityAsync(int sourceID)
{
using (var db = new RPDBContext())
{
return db.Source.FirstOrDefaultAsync(x => x.SourceID == sourceID);
}
}
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