3
How can I make the ands
dynamically in the where
using Linq and entityFramework?
Thanks in advance for any help.
return _dbContext.TbParceiro
//Preciso fazer algo do tipo mas isso não funciona, não sei como posso fazer aqui.
.Where(p =>
if (!string.IsNullOrEmpty(mdlParceiroFiltro.FiltroId))
{
p.ParceiroId = mdlParceiroFiltro.FiltroId;
}
)
.OrderBy(p => p.ParceiroId)
.Skip(mdlParceiroFiltro.Pula)
.Take(mdlParceiroFiltro.Pega)
.ToList();
Below is an example that works by using string command, I need to do the same thing only with String.
sql.Append("SELECT u.Id, u.Nome, u.Usuario ");
sql.Append("FROM usuario u ");
sql.Append("WHERE 1 = 1 ");
if (model != null)
{
if (!string.IsNullOrEmpty(model.Nome))
{
sql.Append("AND u.Nome like @Nome ");
lstParametros.Add(new MySqlParameter() {
ParameterName = "@Nome",
MySqlDbType = MySqlDbType.String,
Value = "%" + model.Nome + "%"
});
}
if (!string.IsNullOrEmpty(model.Usuario))
{
sql.Append("AND u.Usuario like @Usuario ");
lstParametros.Add(new MySqlParameter()
{
ParameterName = "@Usuario",
MySqlDbType = MySqlDbType.String,
Value = "%" +
model.Usuario + "%"
});
}
}
Cool, but in this line "var entities = _dbContext.Tbpartner;" it will not make a full select in the bank?
– Mauricio Ferraz
No, the
dbContext
only executes select when you call a finalizer method, type theToList
orToArray
, for example. While you only add filters, it will mount select without running.– Gabriel
Perfect. Thank you
– Mauricio Ferraz
He complained of a conversion ai instead of me using var put Iqueryable<Partneromodel> entities = _dbContext.Tbpartner;
– Mauricio Ferraz
I got it, I thought
var
would automatically pick up the typeIQueryable
.– Gabriel
I changed the answer to reflect what you commented.
– Gabriel