Home > Net >  same LINQ queries but different tables
same LINQ queries but different tables

Time:08-01

await _context.TableA
                .Where(x => request.A == null || x.A == request.A)
                .Where(x => request.StartDate == null || x.CreatedAt >= request.StartDate)
                .Where(x => request.EndDate == null || x.CreatedAt <= request.EndDate)
                .GroupBy(g => new { g.A, g.B, g.C } )
                .Select(g => new dtoA
                {
                    A = g.Key.A,
                    B = g.Key.B,
                    C = g.C
                })
                .ToListAsync();

And i have same request but to another table

await _context.TableB
                .Where(x => request.A == null || x.A == request.A)
                .Where(x => request.StartDate == null || x.CreatedAt >= request.StartDate)
                .Where(x => request.EndDate == null || x.CreatedAt <= request.EndDate)
                .GroupBy(g => new { g.A, g.B, g.C } )
                .Select(g => new dtoB
                {
                    A = g.Key.A,
                    B = g.Key.B,
                    C = g.C
                })
                .ToListAsync();

Queries are same but tables are different. So question is, how can i combine queries, or create 1 base query?

CodePudding user response:

You could do this if both of your entities implement the same interface with all relevant properties. Same goes for the DTO classes too. For example:

public interface IFoo
{
    string A { get; }
    DateTime CreatedAt { get; }
    // etc
}

And each of your entities must implement that:

public class TableA : IFoo { ... }
public class TableB : IFoo { ... }

The same goes for your DTO classes:

public interface IDto
{
    string A { get; set; }
    string B { get; set; }
    string C { get; set; }
    // etc
}

Now you can make a generic method that takes generic types and constrains them to be the interfaces created above. Also, use the DbSet.Set method to get the correct entity type from the context.

public async Task<List<TDto>> GetData<TEntity, TDto>(Request request)
    where TEntity : class, IFoo
    where TDto : IDto, new()
{
    return await _context.Set<TEntity>()
        .Where(x => request.A == null || x.A == request.A)
        .Where(x => request.StartDate == null || x.CreatedAt >= request.StartDate)
        .Where(x => request.EndDate == null || x.CreatedAt <= request.EndDate)
        .GroupBy(g => new { g.A, g.B, g.C } )
        .Select(g => new TDto
        {
            A = g.Key.A,
            B = g.Key.B,
            C = g.C
        })
        .ToListAsync();
}

Now you call the method like this:

var resultA = await GetData<TableA, dtoA>(request);
var resultB = await GetData<TableB, dtoB>(request);
  • Related