6

我有一个数据库,每“n”秒插入一次 CPU 使用率,我的任务是从数据库中获取最新的 CPU 条目。我想显示属于特定服务器的数据库中的最新 CPU 条目,并且我想将结果保存到通用列表中。

我尝试过的,

    string match = "ServerX"

    List<UsageCPU> cpus = (from a in db.UsageCPUs
                          where a.ServerID.Contains(match)
                          group a by a.ServerID into b
                          orderby b.Key
                          select new { ServerID = b.Key, 
                          Usage = b.FirstOrDefault() }).ToList();

我想遍历结果cpus以执行进一步的其他步骤。

但我收到以下错误

无法将类型“System.Collections.Generic.List<AnonymousType#1>”隐式转换为“System.Collections.Generic.List<FNC_RAQIT_HM_UI.UsageCPU>”。

编辑

在此处输入图像描述 更新 Satpal 的以下查询对我有用.. 但使用var

   var cpus = (from a in db.UsageCPUs
                    where a.ServerID.Contains(match)
                    group a by a.ServerID into b
                    orderby b.Key
                    select new
                    {
                        ServerID = b.Key,
                        Usage = b.FirstOrDefault().Usage
                    }).ToList();

        foreach (var item in cpus)
        {
           if(bla bla..)
        }

请帮助!

4

2 回答 2

12

采用

List<UsageCPU> cpus = (from a in db.UsageCPUs
                      where a.ServerID.Contains(match)
                      group a by a.ServerID into b
                      orderby b.Key
                      select new UsageCPU  //Added UsageCPU  
                      { 
                          ServerID = b.Key, 
                          Usage = b.FirstOrDefault().Usage 
                      }).ToList();

根据错误更新

无法在 LINQ to Entities 查询中构造实体

List<UsageCPU> cpus = (from a in db.UsageCPUs
                      where a.ServerID.Contains(match)
                      group a by a.ServerID into b
                      orderby b.Key
                      select new 
                      { 
                          ServerID = b.Key, 
                          Usage = b.FirstOrDefault().Usage
                      })
                    .AsEnumerable()
                    .Select(x => new UsageCPU  
                    {
                       ServerID ,
                       Usage            
                    }).ToList();
于 2013-06-24T12:48:39.163 回答
3

当您选择新时尝试选择不是新的,您会得到无法强制转换为类型的匿名UsageCPU类型

 (from a in db.UsageCPUs
 where a.ServerID.Contains(match)
 group a by a.ServerID into b
 orderby b.Key
 select a)

或使用 var 然后遍历结果

var cpus = (from a in db.UsageCPUs
                      where a.ServerID.Contains(match)
                      group a by a.ServerID into b
                      orderby b.Key
                      select new { ServerID = b.Key, 
                      Usage = b.FirstOrDefault() }).ToList();
于 2013-06-24T13:16:41.070 回答