【问题标题】:How to create the function using Expression linq如何使用 Expression linq 创建函数
【发布时间】:2012-03-23 20:17:55
【问题描述】:

我有以下课程

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

我需要一个搜索存储库并返回 true 或 false 的函数
但是这个搜索可以使用类的任何字段!

据我所知

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

想用这样的功能...

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

谢谢大家!

【问题讨论】:

  • 这是什么类型的存储库?这还是 Linq to Objects 吗?

标签: c# linq entity-framework lambda expression


【解决方案1】:

我想你正在寻找

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

但你也可以这样做:

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

然后调用:

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

【讨论】:

    【解决方案2】:

    试试:

    public bool Existe<TProperty, TComparer>(Expression<Func<ProdutoTipo, TProperty>> entityExpression, TComparer valor)
    {
        entityExpression.Compile()(Repository.ProdutoTipos);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多