Skip to content

Generic metods for get data #148

@alex23215

Description

@alex23215

Hello, when generating the code for getting a collection of objects from the database. Radzen Studio creates a similar method for each model(table)

public async Task<IQueryable<Item>> GetItems(Query query = null)
{
    var items = Context.Items.AsQueryable();
    if (query != null)
    {
        if (!string.IsNullOrEmpty(query.Expand))
        {
            var propertiesToExpand = query.Expand.Split(',');
            foreach (var p in propertiesToExpand)
            {
                items = items.Include(p.Trim());
            }
        }
        if (!string.IsNullOrEmpty(query.Filter))
        {
            if (query.FilterParameters != null)
            {
                items = items.Where(query.Filter, query.FilterParameters);
            }
            else
            {
                items = items.Where(query.Filter);
            }
        }
        if (!string.IsNullOrEmpty(query.OrderBy))
        {
            items = items.OrderBy(query.OrderBy);
        }
        if (query.Skip.HasValue)
        {
            items = items.Skip(query.Skip.Value);
        }
        if (query.Top.HasValue)
        {
            items = items.Take(query.Top.Value);
        }
    }
    return await Task.FromResult(items);
}

Why don't you use something like this generics-based method to avoid code duplication

public IQueryable<TEntity> GetItems<TEntity>(Func<TEntity,bool>? expForFilter = null, Expression<Func<TEntity, dynamic>>[]? collectionIncludes = null) where TEntity : class
{
    var items = Context.Set<TEntity>().AsQueryable();

    if (collectionIncludes != null)
    {
        
        items = collectionIncludes.Where(x=>x.Body.Type != typeof(string)).Aggregate(items, (current, include) => current.Include(include));
        var stringIncludes = collectionIncludes.Where(x=>x.Body.Type == typeof(string));
        if (stringIncludes is not null && stringIncludes.Any())
        {
            foreach (var includ in stringIncludes.Select(x=>x.Body))
            {
                items = items.Include(includ.ToString());
            }
        }
    }
    
    if (expForFilter != null)
    {
        items = items.AsEnumerable().Where(expForFilter).AsQueryable();
    }
    return items;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions