【问题标题】:Can I convert a Func<T, bool> to a Func<U, bool> where T and U are POCO classes where I can map properties of one to the other? If so, how?我可以将 Func<T, bool> 转换为 Func<U, bool> 其中 T 和 U 是我可以将一个属性映射到另一个的 POCO 类吗?如果是这样,怎么做?
【发布时间】:2013-03-15 20:39:30
【问题描述】:

我有一个场景,其中一个方法将采用 Func 类型的谓词,因为 T 类型是暴露给外部世界的类型,但在实际使用该谓词时我需要该方法来调用另一个方法,该方法将采用 Func 其中 T 的属性映射到 U 的属性。

一个更具体的例子是:

public IEnumerable<ClientEntity> Search(Func<ClientEntity, bool> predicate)
{
    IList<ClientEntity> result = new List<ClientEntity>();

    // Somehow translate predicate into Func<Client, bool> which I will call realPredicate.
    _dataFacade.Clients.Where(realPredicate).ToList().ForEach(c => result.Add(new ClientEntity() { Id = c.Id, Name = c.Name }));

    return result.AsEnumerable();
}

这可能吗?

请注意,ClientEntity 是我自己定义的 POCO 类,而 Client 是模型创建的实体框架类(DB 优先)。

谢谢!

【问题讨论】:

    标签: linq entity-framework-4 linq-to-entities


    【解决方案1】:

    我曾经尝试过这个。当表达式树由更简单的操作(等于、大于、小于等)组成时,它会导致一个不太糟糕的表达式树重写器。

    可以找到here

    您可以将其用作:

    Expression<Func<Poco1>> where1 = p => p.Name == "fred";
    Expression<Func<Poco2>> where2 = ExpressionRewriter.CastParam<Poco1, Poco2>(where1);
    

    【讨论】:

      【解决方案2】:

      EF 不使用 lambda - 它使用 Expression Trees

      Func<T, bool> lambda = ( o => o.Name == "fred" );
      Expression<Func<T, bool>> expressionTree = ( o => o.Name == "fred" );
      

      表达式树是表示给定表达式的内存对象图。

      由于它们只是对象,您可以创建或修改它们。

      这是另一个链接:MSDN: How to: Modify Expression Trees

      【讨论】:

        【解决方案3】:

        我最终做的事情不需要使用表达式树:

        public IEnumerable<ClientEntity> Search(Func<ClientEntity, bool> predicate)
        {
            IList<ClientEntity> result = new List<ClientEntity>();
        
            Func<Client, bool> realPredicate = (c => predicate(ConvertFromClient(c)));        
            _dataFacade.Clients.Where(realPredicate).ToList().ForEach(c => result.Add(ConvertFromClient(c)));
        
            return result.AsEnumerable();
        }
        
        private static ClientEntity ConvertFromClient(Client client)
        {
            ClientEntity result = new ClientEntity();
        
            if (client != null)
            {
                // I actually used AutoMapper from http://automapper.org/ here instead of assigning every property.
                result.Id = client.Id;
                result.Name = client.Name;
            }
        
            return result;
        }
        

        【讨论】:

          猜你喜欢
          • 2021-08-25
          • 1970-01-01
          • 2023-03-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-31
          相关资源
          最近更新 更多