Question

I am looking for a way to access a variable column using a specified value. I have a data structure that matches 1:1 to my SQL database:

class Message
{
    int MessageId;
    string MessageType;
    /* more fields */

    double? Metric1;
    double? Metric2;
    /* cont'd */
    double? Metric10;

    /* database computed values */
    int Year;   
    int Month;
    int Day;    
}

How would I, using LINQ to SQL, do aggregation (Sum, Average) on a specific "Metric n" field based on the value of a variable?

Example:

/* DataContext Messages; */
int metric = 2;

var results = Messages
    .GroupBy(m => new { m.Year, m.Month })
    .Select(g => new {
        Year = g.Key.Year,
        Metric = g.Sum(m => m.MetricN) /* Here, MetricN should reflect the 
                                          value of (int metric) ("Metric" + metric) */
    });

Requirements:

  • (int metric) is dynamically set (not known in advance, i.e. I am fetching the value from a Metrics definition table, based on a name).
  • MetricN fields will always be of the same type.
  • Fluent syntax preferred.

I know that putting the metrics in a separate table (with columns (MessageID, Metric and Value) would simplify requests, but this is the data structure I have to work with.

Is my only solution to hand-write my SQL requests?

Était-ce utile?

La solution

Look into using Dynamic LINQ. It allows you to use string expressions instead of Lambda expressions.

It would end up looking something like this:

var results = Messages
    .GroupBy(m => new { m.Year, m.Month })
    .Select("new (Key.Year as Year, Sum(Metric1) as Metric)");

You'd just have to generate the select expression string outside of the query however you want to do that.

There is a version if Dynamic LINQ on Nuget here: https://www.nuget.org/packages/System.Linq.Dynamic.Library/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top