AsValeO
AsValeO

Reputation: 3039

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

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

Upvotes: 9

Views: 13627

Answers (3)

Liviu Sosu
Liviu Sosu

Reputation: 1547

The approved answer is correct, but not the best from my point of view.

If you are searching by the id, use the Find(PropertyID) method like this:

db.Source.Find(SourceID)

where:

  • db: database context
  • Source: your entity type
  • SourceId is the Primary key

It returns the object or null, if not found. More details here: https://learn.microsoft.com/en-us/ef/ef6/querying/#:~:text=The%20Find%20method%20on%20DbSet,context%20or%20in%20the%20database.

Upvotes: 5

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

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.

Upvotes: 6

Kevin Gosse
Kevin Gosse

Reputation: 39007

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

Upvotes: 2

Related Questions