Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 608
AsValeO Avatar asked Mar 05 '16 14:03

AsValeO


People also ask

How do you load related entities in EF?

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.

How do I load related data in EF core?

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.

What is the way of loading data in Entity Framework?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

What difference does AsNoTracking () make?

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.


2 Answers

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.

like image 180
Hamid Pourjam Avatar answered Oct 30 '22 15:10

Hamid Pourjam


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);
    }
}
like image 39
Kevin Gosse Avatar answered Oct 30 '22 16:10

Kevin Gosse