I’m using EF (4.4) and have a flat table with N columns named Value1 … ValueN.
Based on another column (ValueIndex) I need to grab the three columns with N values of ValueN-1, ValueN, and ValueN+1
For example if ValueIndex is 3 I need to get Value2, Value3, and Value4.
For the sake of simplicity assume ValueIndex is free from bounds issue, i.e. not 1 or N and that I have 7 Value columns.
If this was in memory I would do (and probably will do) something like this:
table.Select(t =>
new {
ValueIndex = t.ValueIndex,
Values = new[] {
Value1, Value2, Value3, Value4, Value5, Value6, Value7
}
})
.Select(t =>
new[] {
Values[ValueIndex-1], Values[ValueIndex], Values[ValueIndex+1]
}
);
Unfortunately this won’t work in EF due to the array indices being unsupported.
As a workaround I tried replacing the array indices with an indexer select:
.Select(t =>
new[] {
t.Values.Where((v, i) => i == t.ValueIndex-1).First(),
t.Values.Where((v, i) => i == t.ValueIndex).First(),
t.Values.Where((v, i) => i == t.ValueIndex+1).First(),
}
);
But unfortunately that isn’t supported either (LINQ to Entities does not recognize the Where method on the t.Values variable).
I don’t especially want a gigantic switch statement in my code:
tables.Select(t =>
new[] {
t.ValueIndex == 2 ?
new[] {
t.Value1,
t.Value2,
t.Value3,
}
: t.ValueIndex == 3 ?
new[] {
t.Value2,
t.Value3,
t.Value4,
}
: // Etc..
}
);
So is there any way to achieve the query I’m after using EF (i.e. convertible to SQL) in a manner other than a massive switch/case?
Entity Framework (and many ORMs) are designed for relational databases. In other situations (document stores, or key value stores), they tend to fall apart…
That said, if you Entity Framework is still the right tool here, think about how this would possibly be handled in SQL… It sounds sort of like a pivot to me.
So…can you build this in LINQ? Sure…
Kind of ugly though…
If you wanted to make it sustainable, you could build the expression tree above out dynamically fairly easily.
So you could have something like