How to add includes by expression in repository pattern C #

0

I'm creating a RepositoryBase (Repository Pattern) with EntityFramework Asp.Net Core, and in it I'm creating a Where method, where I pass an entity where expression. So far the method works perfectly, but in this same method I would like to pass an includes expression to be added before the SQL is performed.

Example:

public class RepositoryBase<TEntity> : IRepositoryBase<TEntity>
    where TEntity : EntityBase
{
    public RepositoryBase()
    {
        SetDbContext();
    }

    public void SetDbContext()
    {
        DbContext = new AberturaDeContasContextFactory().CreateDbContext();
    }

    public DbContext DbContext { get; set; }

    public string MessageError = "Erro ao {0}. Source: {1}, Exception: {2} ";

    public ICollection<TEntity> Where<TProperty>(Expression<Func<TEntity, bool>> where, params Expression<Func<TEntity, TProperty>>[] properties)
        where TProperty : EntityBase
    {
        try
        {
            var source = DbContext.Set<TEntity>().Where(where);

            if (!properties.IsObjectNull())
            {
                foreach (var prop in properties)
                {
                    source.Include(prop);
                }
            }
            return source.ToList();
        }
        catch (Exception ex)
        {
            throw new Exception(string.Format(MessageError, "Pesquisar todos com where", ex.Source, ex.Message));
        }
    }
}
  

When performing SQL, include is not working

public class HomeController : Controller
{
    public IActionResult Index()
    {
        Repository.Repositories.RepositoryBase<Cliente> repositorio = new Repository.Repositories.RepositoryBase<Cliente>();

        var a = repositorio.Where<Documento>(x => x.ClienteId == 1, doc => doc.Documento).ToList();

        return View();
    }
}
    
asked by anonymous 13.08.2018 / 19:41

1 answer

1

I do this as follows:

public virtual List<TEntity> SelectIncludes(Func<TEntity, bool> where, params Expression<Func<TEntity, object>>[] includes)
{
    IQueryable<TEntity> query = _context.Set<TEntity>();

    IEnumerable<TEntity> resultado = includes.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));


    if (where != null)
        resultado = resultado.Where(where);

    return resultado.ToList();
}

To call it:

MinhaClasse minhaClasse = _meuRepositorio.SelectIncludes(p=> p.Id == 1, i=> i.ClasseRelacionadaUm, i=> i.ClasseRelacionadaDois).FirstOrDefault();

You may need to make some adjustments for how you are implementing pattern .     

13.08.2018 / 19:48