radzen-blazor-studio icon indicating copy to clipboard operation
radzen-blazor-studio copied to clipboard

Generic metods for get data

Open alex23215 opened this issue 1 year ago • 0 comments

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

alex23215 avatar Oct 02 '24 09:10 alex23215