Entity Framework Core (7): load single entity by id

.net async-await c# entity-framework entity-framework-core

Question

.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();
    }
}
1
4
3/5/2016 3:17:53 PM

Accepted Answer

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.

4
3/5/2016 3:17:20 PM

Popular Answer

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);
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow