I have a method in which I need to pass only one select per parameter:
public List<TEntity> GetAll(Expression<Func<TEntity, TEntity>> Select)
{
var query = Context.Set<TEntity>()
.Where()
.Select(Select).ToList();
return query;
}
I need to pass a select that brings me the following fields: UsuarioId, Login, Senha, UsuarioTipoId e Descricao
. It would look something like this:
dgPesquisar.DataSource = UsuarioRepositorio.GetAll(u => new
{
x.UsuarioId,
x.Login,
x.Senha,
x.UsuarioTipoId,
x.Descricao
});
Is it necessary to do some Join in the tables?
Would anyone know how to help me assemble the expression and how to pass it by parameter?
//Classes:
public class UsuarioTipoModel
{
public int UsuarioTipoId { get; set; }
public string Descricao { get; set; }
public virtual ICollection<UsuarioModel> Usuario { get; set; }
}
public class UsuarioModel : PessoaModel
{
public string Login { get; set; }
public string Senha { get; set; }
public int UsuarioTipoId { get; set; }
public virtual UsuarioTipoModel UsuarioTipo { get; set; }
}
Repository
public abstract class BaseRepository<TEntity> : Interfaces.IRepository<TEntity> where TEntity : class
{
private DbContext Context = null;
protected DbSet<TEntity> Entity = null;
public BaseRepository(DbContext Context)
{
this.Context = Context;
this.Entity = Context.Set<TEntity>();
}
public void Add(TEntity Entity)
{
Context.Set<TEntity>().Add(Entity);
Context.SaveChanges();
}
public void Delete(TEntity Entity)
{
Context.Set<TEntity>().Remove(Entity);
Context.SaveChanges();
}
public TEntity Find(int Id)
{
var query = Context.Set<TEntity>().Find(Id);
return query;
}
public List<TEntity> GetAll()
{
var query = Context.Set<TEntity>().ToList();
return query;
}
public List<TEntity> GetAll(Expression<Func<TEntity, bool>> Predicate)
{
var query = Context.Set<TEntity>().Where(Predicate).ToList();
return query;
}
public List<TEntity> GetAll(Expression<Func<TEntity, bool>> Predicate, Expression<Func<TEntity, TEntity>> Select)
{
var query = Context.Set<TEntity>()
.Where(Predicate)
.Select(Select).ToList();
return query;
}
public void Update(TEntity Entity)
{
Context.Entry(Entity).State = EntityState.Modified;
Context.SaveChanges();
}
}