Grouping on dynamic columns in LINQ to SQL

May 28 2014 5:21 AM
I have a SQLite database which I'm running LINQ to SQL queries on. The following query works fine when I know that I want to group by "Dim1" and "Dim2". The problem is that the columns to group by are set dynamically. Now, I've googled around for samples using Dynamic LINQ but I can't seem to solve my problem. Any help will be great..  This is as far as I've come..
 
var query = (from bl in DatabaseConnection.DataMemoryContext.GetTable<BudgetLineEntity>()
where bl.BudgetID == filter.BudgetId && bl.BudgetType == filter.BudgetType
group bl by new { FirstDimensionName=primaryDimension.Name,SecondDimensionName=secondaryDimension.Name } into DimGroup
//group bl by new { Dimension1 = primaryDimension.Name, Dimension2 = secondaryDimension.Name } into DimGroup
select new BudgetData
{
Dim1 = DimGroup.Key.FirstDimensionName,
Dim2 = DimGroup.Key.SecondDimensionName,
Sum = DimGroup.Sum(grp => (System.Single)grp.Value1)
}).ToList(); 
 
I've also tried, but then res2 is null!?
var res2 =
DatabaseConnection.DataMemoryContext.GetTable<BudgetLineEntity>().AsQueryable()
.GroupBy("Dim1","it")
.Select("new (Key as Dim1,Key as Dim2, Sum(Value1) as Sum)")
as IQueryable<BudgetData>; 
 
my BudgetData looks like this 
public class BudgetData
{
public string Dim1 { get; set; }
public string Dim2 { get; set; }
public float Sum { get; set; }
 
my BudgetLineEntity looks like this
 
[Table(Name = "BudgetLine")]
public class BudgetLineEntity
{
[Column(Name = "BudgetLineID")]
public int BudgetLineID { get; set; }

[Column(Name = "BudgetID")]
public int BudgetID { get; set; }

[Column(Name = "BudgetType")]
public int BudgetType { get; set; }

[Column(Name = "Year")]
public int Year { get; set; }

[Column(Name = "Period")]
public int Period { get; set; }

[Column(Name = "Dim1")]
public string Dim1 { get; set; }

[Column(Name = "Dim2")]
public string Dim2 { get; set; }

[Column(Name = "Dim3")]
public string Dim3 { get; set; }

[Column(Name = "Dim4")]
public string Dim4 { get; set; }

[Column(Name = "Dim5")]
public string Dim5 { get; set; }

[Column(Name = "Value1")]
public System.Single Value1 { get; set; }
}
 

Answers (10)