【问题标题】:Tunning my dash board linq query调整我的仪表板 linq 查询
【发布时间】:2014-01-15 00:52:41
【问题描述】:

我在我的 asp.net mvc web 应用程序中有以下 linq 查询,它主要通过显示许多实体的 count() 来构建我们的仪表板:-

public SystemInformation GetSystemInfo(int pagesize) 

        {
            var d = DateTime.Today;
            string[] notservers = new string[] { "vmware virtual platform", "storage device", "router", "switch", "firewall" };
            string[] types = new String[] { "server", "workstation" };

            var tmpCustomCount = tms.CustomAssets.Sum(a => (int?)a.Quantity);
            SystemInformation s = new SystemInformation()
            {

            AssetCount = new AssetCount() {

                CustomerCount = entities.AccountDefinitions.Count(),
                RackCount = tms.TMSRacks.Count(),
                ServerCount =  tms.TMSServers.Count(),
                VirtualMachineCount =  tms.TMSVirtualMachines.Count(),
                StorageDeviceCount =  tms.TMSStorageDevices.Count(),
                FirewallCount = tms.TMSFirewalls.Count(),
                SwitchCount =  tms.TMSSwitches.Count(),
                RouterCount =  tms.TMsRouters.Count(),
                DataCenterCount =  tms.DataCenters.Count(),
                CustomCount = tmpCustomCount == null ? 0 : tmpCustomCount.Value
                //tms.CustomAssets==null? 0 : tms.CustomAssets.Sum(a => a.Quantity)

            },

           AdminAudit = AllIncludingAdminAudit("", auditinfo => auditinfo.SecurityTaskType, auditinfo2 => auditinfo2.AuditAction).OrderByDescending(a => a.DateTimeStart)
           .Take(pagesize).ToList(),
           LatestTechnology = tms.Technologies.Where(a=> !a.IsDeleted && a.IsCompleted).OrderByDescending(a => a.TechnologyID).Take(pagesize).ToList(),
           IT360ServerNo =     entities.Resources
            .Where(a => String.IsNullOrEmpty(a.ASSETTAG) && (a.SystemInfo.ISSERVER == true ) && !(notservers.Contains(a.SystemInfo.MODEL.Trim().ToLower()))).Count(),
            IT360VMNo = entities.Resources
            .Where(a => String.IsNullOrEmpty(a.ASSETTAG) && (a.SystemInfo.ISSERVER == true) && a.SystemInfo.MODEL.Trim().Equals("VMware Virtual Platform", StringComparison.OrdinalIgnoreCase)).Count(),
            IT360SDNo = entities.Resources
           .Where(a => String.IsNullOrEmpty(a.ASSETTAG) && a.SystemInfo.MODEL.Trim().Equals("Storage Device", StringComparison.OrdinalIgnoreCase)).Count(),
            IT360SwitchNo = entities.Resources
            .Where(a => String.IsNullOrEmpty(a.ASSETTAG) && a.SystemInfo.MODEL.Trim().Equals("Switch", StringComparison.OrdinalIgnoreCase)).Count(),
            IT360FirewallNo = entities.Resources
           .Where(a => String.IsNullOrEmpty(a.ASSETTAG) && a.SystemInfo.MODEL.Trim().Equals("Firewall", StringComparison.OrdinalIgnoreCase)).Count(),
            IT360RouterNo = entities.Resources
           .Where(a => String.IsNullOrEmpty(a.ASSETTAG) && a.SystemInfo.MODEL.Trim().Equals("Router", StringComparison.OrdinalIgnoreCase)).Count(),

            DeleteNo = tms.TechnologyAudits.Where(a => ( EntityFunctions.TruncateTime(a.DateTimeEnd) == d && a.AuditAction.Name.ToLower() == "delete" && a.TechnologyID != null)).Count(),//TechnologyId != null so that only assets that have tags will be included in the count
            CreateNo = tms.TechnologyAudits.Where(a => (EntityFunctions.TruncateTime(a.DateTimeEnd) == d && a.AuditAction.Name.ToLower() == "add" && a.TechnologyID != null)).Count(),
            EditNo = tms.TechnologyAudits.Where(a => (EntityFunctions.TruncateTime(a.DateTimeEnd) == d && a.AuditAction.Name.ToLower() == "Edit" && a.TechnologyID != null)).Count(),
            OtherNo = tms.TechnologyAudits.Where(a => (EntityFunctions.TruncateTime(a.DateTimeEnd) == d 
                && 
               !((a.AuditAction.Name.ToLower() == "delete" && a.TechnologyID != null) 
               || (a.AuditAction.Name.ToLower() == "add" && a.TechnologyID != null) 
               || (a.AuditAction.Name.ToLower() == "edit" && a.TechnologyID != null)))).Count(),


            };
            return s;
        }

模型类是:-

public class SystemInformation
    {
        public AssetCount AssetCount { get; set; }
        public  IPagedList<TechnologyAudit> TechnologyAudit { get; set; }
        public ICollection<AdminAudit> AdminAudit { get; set; }
        public ICollection<Technology> LatestTechnology { get; set; }
        [Display(Name = "Server/s")]
        public int IT360ServerNo { get; set; }
        [Display(Name = "VM/s")]
        public int IT360VMNo { get; set; }
        [Display(Name = "SD/s")]
        public int IT360SDNo { get; set; }
        [Display(Name = "Switch/s")]
        public int IT360SwitchNo { get; set; }
        [Display(Name = "Firewall/s")]
        public int IT360FirewallNo { get; set; }
        [Display(Name = "Router/s")]
        public int IT360RouterNo { get; set; }
        [Display(Name = "Delete Opeartion/s")]
        public int DeleteNo { get; set; }
        [Display(Name = "Create Opeartion/s")]
        public int CreateNo { get; set; }
        [Display(Name = "Edit Opeartion/s")]
        public int EditNo { get; set; }
        [Display(Name = "Other Opeartion/s")]
        public int OtherNo { get; set; }

        public Double HourSpan { get; set; }
        public int RefreshInSeconds { get; set; }
    }

以上运行良好,但问题是我正在向数据库发送单独的查询以填充每个变量,例如 customercount、RackCount、ServerCount 等... 我知道使用单个查询来构建上述内容可能是不可能的,因为我正在从单独的表中检索 count()。但是有没有办法将同一张表上的 Count() 加入单个查询,我的意思是使用诸如 GroupBy 之类的东西并根据关键位置返回计数?

【问题讨论】:

    标签: c# linq asp.net-mvc-4 entity-framework-4


    【解决方案1】:

    GroupBy 可用于计算与指定键相关的组数。在您的示例中,您在等于字符串键之后或之前使用了许多额外的过滤。您可以尝试以下情况,但在其他情况下,很难有效地应用 GroupBy:

    var ActionCounts = tms.TechnologyAudits.Where(a =>
        (EntityFunctions.TruncateTime(a.DateTimeEnd) == d && a.TechnologyID != null))
        .GroupBy(a => a.AuditAction.Name.ToLower())
        .Select(g => new {
            Action = g.Key
            ItemCount = g.Count();
        }).ToLookup(a => a.Action);
    

    如何与您的代码集成:

    var tmpCustomCount = tms.CustomAssets.Sum(a => (int?)a.Quantity);
    
    [Insert here:]
    
            SystemInformation s = new SystemInformation()
    
    ...
    
    DeleteNo = ActionCounts["delete"] == null ? 0 : ActionCounts["delete"].Single().ItemCount;
    CreateNo = ActionCounts["add"] == null ? 0 : ActionsCount["add"].Single().ItemCount;
    EditNo = ActionCounts["edit"] == null ? 0 : ActionsCount["edit"].Single().ItemCount;
    

    【讨论】:

    • 但是这样我将在构建 ActionGroup 变量时从服务器检索所有数据,而我需要的是 count()。
    • ActionCount 的类型是什么,可以是 Var 吗??
    • 我将如何获得 ActionCounts 的值??
    • 您更新的代码运行良好,但如果 TechnologyAudit 没有 action = delete(没有人执行删除操作),那么 ActionCounts["delete"].Single().ItemCount 将始终返回一个例外。如果有办法解决这个问题,你能建议吗?
    猜你喜欢
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多