Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to reuse part of Linq to Entity Select expression in EF4.1 code only scenario
    primarykey
    data
    text
    <p>Here is very simplified version of code that i have:</p> <pre><code>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; } } </code></pre> <p>Then i have 2 queries:</p> <pre><code>var repo = new Repository(...); var q1 = repo.GetQuery&lt;PrintJob&gt;() .GroupBy(pj =&gt; pj.UserName) .Select(g =&gt; new PrintJobByUserReportItem { #region this is PrintJobReportItem properties TotalPagesPrinted = g.Sum(p =&gt; p.PagesPrinted), AveragePagesPrinted = g.Average(p =&gt; p.PagesPrinted), PercentOfSinglePagePrintJobs = g.Count(p =&gt; p.PagesPrinted == 1) / (g.Count(p =&gt; p.PagesPrinted) != 0 ? g.Count(p =&gt; p.PagesPrinted) : 1) * 100, #endregion UserName = g.Key }); var q2 = repo.GetQuery&lt;PrintJob&gt;() .GroupBy(pj =&gt; pj.Departmen) .Select(g =&gt; new PrintJobByDepartmenReportItem { #region this is PrintJobReportItem properties TotalPagesPrinted = g.Sum(p =&gt; p.PagesPrinted), AveragePagesPrinted = g.Average(p =&gt; p.PagesPrinted), PercentOfSinglePagePrintJobs = g.Count(p =&gt; p.PagesPrinted == 1) / (g.Count(p =&gt; p.PagesPrinted) != 0 ? g.Count(p =&gt; p.PagesPrinted) : 1) * 100, #endregion DepartmentName = g.Key, NumberOfUsers = g.Select(u =&gt; u.UserName).Distinct().Count() }); </code></pre> <p>What would be suggestions for extracting parts where i assign values to TotalPagesPrinted, AveragePagesPrinted and PercentOfSinglePagePrintJobs out from those 2 queries, so that it can be reused and would follow DRY principle.</p> <p>I'm using EF 4.1 code only approach and switching to another technology or approach is not an option. Also i cannot materialize that data, i need to keep it as query, because my grid component will add more things to query later, so i can't switch to Linq to Object.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload