0

I have an ASP.NET Core project with SQL as database. My question is why does this code (using an anonymous type):

var libraries = await _repo.GetAllDynamicAsync<Library>(
    column: c => new { c.Application, c.CreatedBy, c.CreatedDate, c.Description, c.Id, c.ModifiedBy, c.ModifiedDate, c.Name, c.NormalizeName, c.RowVersion, c.isDeleted });

query much faster than this code (using a class instance):

var libraries = await _repo.GetAllDynamicAsync<Library>(
    column: c => c );

Both snippets of code return the same data.

Other code:

public class Library : ExtendedEntity<int>
{
    public string Name { get; set; }
    public string NormalizeName { get; set; }
    public string Description { get; set; }
    public bool isDeleted { get; set; }
    public virtual ICollection<DocumentGroup> DocumentGroup { get; set; }
    public string Application { get; set; }
}

private IQueryable<TEntity> GetQueryable<TEntity>(
    Expression<Func<TEntity, bool>> filter = null,
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
    int? skip = null, int? take = null, bool asNoTracking = false,
    Func<IQueryable<TEntity>, IIncludableQueryable<TEntity, object>> include = null)
    where TEntity : class, IEntity
{
    IQueryable<TEntity> query = _context.Set<TEntity>();
        
    if (filter != null)
        query = query.Where(filter);

    if (include != null)
        query = include(query);

    if (orderBy != null)
        query = orderBy(query);

    if (skip.HasValue)
        query = query.Skip(skip.Value);

    if (take.HasValue)
        query = query.Take(take.Value);

    if (asNoTracking)
        query = query.AsNoTracking();

    return query;
}

public virtual async Task<DbEntity> GetAllDynamicAsync<TEntity>(
    Expression<Func<TEntity, bool>> filter = null,
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
    int? skip = null, int? take = null, bool asNoTracking = false,
    Func<IQueryable<TEntity>, IIncludableQueryable<TEntity, object>> include = null,
    Expression<Func<TEntity, dynamic>> column = null)
    where TEntity : class, IEntity
{
    DbEntity dbEntity = new DbEntity();
    dbEntity.Count = await GetQueryable<TEntity>(filter, orderBy, null, null, asNoTracking, include).Select(column).CountAsync();
    dbEntity.Data = await GetQueryable<TEntity>(filter, orderBy, skip, take, asNoTracking, include).Select(column).ToListAsync();
    return dbEntity;
}

Can someone please explain this? Why is the code using an anonymous type faster than the code using the an object itself?

Also kindly note that I'm new to Entity Framework. So if you think I'm doing it wrong or there's a better way to do querying, please kindly let me know. Thank you!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

0 Answers0