gpt4 book ai didi

c# - 如何在仅 EF4.1 代码场景中重用部分 Linq to Entity Select 表达式

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:01 25 4
gpt4 key购买 nike

这是我拥有的非常简化的代码版本:

class PrintJob : IEntity
{
public string UserName { get; set; }
public string Departmen { get; set; }
public int PagesPrinted { get; set; }
}

class PrintJobReportItem
{
public int TotalPagesPrinted { get; set; }
public int AveragePagesPrinted { get; set; }
public int PercentOfSinglePagePrintJobs { get; set; }
}

class PrintJobByUserReportItem : PrintJobReportItem
{
public string UserName { get; set; }
}

class PrintJobByDepartmenReportItem : PrintJobReportItem
{
public string DepartmentName { get; set; }
public int NumberOfUsers { get; set; }
}

然后我有两个问题:

var repo = new Repository(...);

var q1 = repo.GetQuery<PrintJob>()
.GroupBy(pj => pj.UserName)
.Select(g => new PrintJobByUserReportItem
{
#region this is PrintJobReportItem properties
TotalPagesPrinted = g.Sum(p => p.PagesPrinted),
AveragePagesPrinted = g.Average(p => p.PagesPrinted),
PercentOfSinglePagePrintJobs = g.Count(p => p.PagesPrinted == 1) / (g.Count(p => p.PagesPrinted) != 0 ? g.Count(p => p.PagesPrinted) : 1) * 100,
#endregion
UserName = g.Key
});

var q2 = repo.GetQuery<PrintJob>()
.GroupBy(pj => pj.Departmen)
.Select(g => new PrintJobByDepartmenReportItem
{
#region this is PrintJobReportItem properties
TotalPagesPrinted = g.Sum(p => p.PagesPrinted),
AveragePagesPrinted = g.Average(p => p.PagesPrinted),
PercentOfSinglePagePrintJobs = g.Count(p => p.PagesPrinted == 1) / (g.Count(p => p.PagesPrinted) != 0 ? g.Count(p => p.PagesPrinted) : 1) * 100,
#endregion
DepartmentName = g.Key,
NumberOfUsers = g.Select(u => u.UserName).Distinct().Count()
});

从这 2 个查询中提取我为 TotalPagesPrinted、AveragePagesPrinted 和 PercentOfSinglePagePrintJobs 赋值的部分有什么建议,以便它可以重复使用并遵循 DRY 原则。

我只使用 EF 4.1 代码方法,无法切换到另一种技术或方法。此外,我无法具体化该数据,我需要将其保留为查询,因为我的网格组件稍后会添加更多内容进行查询,因此我无法切换到 Linq to Object。

最佳答案

我将创建一个具有两个属性的新类 CLASSNAME

  • PrintJobReportItem 类型
  • 分组 IEnumerable<IGrouping<TKey, TSource>>

然后创建一个扩展方法

public static IQueryable<CLASSNAME> EXTENSIONNAME<TKey, TSource>(this IEnumerable<IGrouping<TKey, TSource>> source)
{
return from g in source
select new CLASSNAME
{
PrintJobReportItem = new PrintJobReportItem
{
TotalPagesPrinted = g.Sum(p => p.PagesPrinted),
AveragePagesPrinted = etc...,
PercentOfSinglePagePrintJobs = etc...,
},
GROUPING = g
};
}

然后像这样使用,我没有测试过,但我认为它会起作用

var q1 = repo.GetQuery<PrintJob>()
.GroupBy(pj => pj.UserName)
.EXTENSIONNAME()
.Select(g => new PrintJobByDepartmenReportItem
{
PrintJobReportItem = g.PrintJobReportItem,
DepartmentName = g.GROUPING.Key,
NumberOfUsers = g.GROUPING.Select(u => u.UserName).Distinct().Count()

});

关于c# - 如何在仅 EF4.1 代码场景中重用部分 Linq to Entity Select 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6281825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com