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