【问题标题】:Using Aggregate to wire linq to put result in POCO使用 Aggregate 连接 linq 将结果放入 POCO
【发布时间】:2012-08-09 16:57:05
【问题描述】:

使用 EF4,我试图想出一种更智能的方式将数据从实体聚合到业务对象,即连接 linq 以将数据直接传递到我的 BE,从而节省了在 linq 之后从 IEnumerable 进行复制的步骤。我一直在尝试使用以下内容,但似乎无法正确使用语法。 CustomerBE 是一个普通的 POCO。

        var customers = uow
               .GetAllCustomers()
               .Aggregate((list,obj) => new List<CustomerBE>()
               {
                  var beo = new CustomerBE { FirstName = obj.Firstname,
                                             Id = obj.Id
                                              ...
                                           };
                  list.Add(beo);
                  return list; 
               });

【问题讨论】:

  • 通常最好避免在 LINQ 查询中引起副作用(将项目添加到聚合调用内的列表中)。这与它的设计背道而驰。您应该根据查询返回创建的对象,而不是修改其中的某些内容。

标签: c# linq entity-framework poco aggregate


【解决方案1】:

为什么不在Select 语句中这样做呢? Select 旨在从一种类型映射到另一种类型:

var customers = uow
           .GetAllCustomers()
           .AsEnumerable()
           .Select(c => new CustomerBE { FirstName = c.Firstname,
                                         Id = c.Id
                                          // ...
                                       }
                  )
           .ToList();

【讨论】:

  • 这正是我一直在寻找的东西,我想我被称为 Aggregation 的方法引向了错误的道路,我认为我应该使用它,因为这是我想要做的,而不是选择。
  • @aggaton - 聚合在 map/reduce 俚语中的意思是“减少”。它负责产生一个超出集合的标量值(Sum、Count、Max 等)。选择就是你要找的
  • @aggaton AZ 是对的——聚合是“减少”,选择是“映射”——你试图从一种类型“映射”到另一种类型,这正是 select 所做的......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 1970-01-01
  • 2022-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多