Generic method in DbSet of DbContext with Entity Framework

3

I have an application in C# that uses Entity Framework .

All my DbSet of DbContext , I extend them to have a default search for the grid, below method example.

public static GridDTO GridPadrao(this DbSet<Cliente> entities, ParametrosGridDTO parametros, UsuarioLogadoDTO usuarioLogado) 
{
  // Código de busca
}

But to make the call I do as below, I have to put if for each DbSet .

else if (parametros.tipoPesquisa == "Cliente")
    return db.Cliente.GridPadrao(parametros, usuarioLogado);
else if (parametros.tipoPesquisa == "Filial")
    return db.Filial.GridPadrao(parametros, usuarioLogado);

Doubt

Is there any way I can call GridPadrao generically? No need to put if for every DbSet that exists in DbContext .

Examples

public static GridDTO GridPadrao(this DbSet<Cliente> entities, ParametrosGridDTO parametros, UsuarioLogadoDTO usuarioLogado)
{
    return new GridDTO(
        entities
            .Where(w => w.Apagado == "N" && w.VisaoID == usuarioLogado.VisaoID)
            .Where(MontaWhere(parametros), parametros.filtro.ToLowerNull())
            .Select(s => new { s.ClienteID, Nome = s.Pessoa.Nome, CNPJCPF = s.Pessoa.CNPJCPF, Fixo = s.Fixo == "S" ? "Sim" : "Não" })
            .OrderBy(MontaOrderBy(parametros))
            .Skip(parametros.itensParaIgnorar)
            .Take(parametros.itensPorPagina)
            .ToArray(),
        entities.TotalDeRegistros(parametros, usuarioLogado)
    );
}

and

public static GridDTO GridPadrao(this DbSet<Funcao> entities, ParametrosGridDTO parametros, UsuarioLogadoDTO usuarioLogado)
{
    var setorID = Convert.ToInt32(parametros.filtrofixo);

    return new GridDTO(
        entities
            .Where(w => w.SetorID == setorID && w.Apagado == "N" && w.VisaoID == usuarioLogado.VisaoID)
            .Where(MontaWhere(parametros), parametros.filtro.ToLowerNull())
            .Select(s => new { s.FuncaoID, s.Sigla, s.Descricao })
            .OrderBy(MontaOrderBy(parametros))
            .Skip(parametros.itensParaIgnorar)
            .Take(parametros.itensPorPagina)
            .ToArray(),
        entities.TotalDeRegistros(parametros, usuarioLogado)
    );
}
    
asked by anonymous 17.06.2016 / 13:31

1 answer

5
  

Is there any way I can call GridPadrao generically?

Yes. Using generics.

public static DbSetExtensions
{
    public static GridDTO GridPadrao<T>(this IDbSet<T> entities, ParametrosGridDTO parametros, UsuarioLogadoDTO usuarioLogado)
        where T: class
    {
        // Código
    }
}

The problem is that you used a lot of strong typing there. Possibly the method will have to be integer redrawn to work generically.

    
17.06.2016 / 16:58