How to create the function using Expression linq

2019-07-17 01:14发布

I have the following class

public class ProdutoTipo : IAuditable
{
    public Guid ID { get; set; }

    public string Nome { get; set; }
    public string MiniNome { get; set; }
    public string Descricao { get; set; }
    public string Link { get; set; }
    public int? Ordem { get; set; }

    public virtual Foto ImagemExibicao { get; set; }
    public virtual ICollection<ProdutoCategoria> Categorias { get; set; }

    public DateTime CreatedAt { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? UpdatedAt { get; set; }
    public string UpdatedBy { get; set; }

    public bool PaginaInicial { get; set; }

    public ProdutoTipo() { ID = Guid.NewGuid(); }
}

I need a function that search the repository and returns true or false
But this search can be using any field of the class!

As far as I arrived

public bool Existe<TProperty, TComparer>(Expression<Func<ProdutoTipo, TProperty>> entityExpression, TComparer valor)
{
    return Repository.ProdutoTipos.Any(p => /*entityExpression == valor ?????*/);
}

Would like to use the function like this ...

Existe(p => p.Nome, "Value to comparer!");

Thank you all!

2条回答
Bombasti
2楼-- · 2019-07-17 02:04

Try:

public bool Existe<TProperty, TComparer>(Expression<Func<ProdutoTipo, TProperty>> entityExpression, TComparer valor)
{
    entityExpression.Compile()(Repository.ProdutoTipos);
}
查看更多
冷血范
3楼-- · 2019-07-17 02:07

I think you're looking for

Func<ProdutoTipo, TProperty> getter = entityExpression.Compile();
Repository.ProdutoTipos.Any(p => getter(p).Equals(valor)); 

But you might as well do this:

public bool Existe<TProperty, TComparer>(Expression<Func<ProdutoTipo, bool>> expression)  
{  
    return Repository.ProdutoTipos.Any(expression);  
}

And call:

Existe(p => p.Nome == "Value to comparer!");  
查看更多
登录 后发表回答