Search code examples
c#databaselinqentity-frameworknotsupportedexception

LINQ Lambda, Group by with list


I'm having some trouble with finding the right syntax to accomplish the following:

Is it possible with LINQ (Lambda Expression) to .GroupBy data and instead of using the usual .Sum() or .Count() I want the resulting data to be a List of Int.

I defined my own class named: Filter_IDs. Its constructor needs two parameters:

public int? type; // Represents the object_type column from my database
public List<int?> objects; // Represents the object_id column from my database

I want to load data from my database into this object. The following LINQ query should result in a List of Filter_IDs:

The following LINQ query should result in a List of Filter_IDs:

List<Filter_IDs> filterids = ef.filterLine
        .GroupBy(fl => fl.objectType)
    .Select(fl => new Filter_IDs { type = fl.Key, objects = fl.Select(x => x.object_id).ToList() })
    .ToList();

Using this query gives no building error but gives an 'NotSupportedException' on RunTime.

The database looks like this to give you a better understanding of the data:

http://d.pr/i/mnhq+ (droplr image)

Thanks in advance, Gerben


Solution

  • I think the problem is the DB is not able to call ToList in the select, nor to create a new Filter_ID.

    Try something like this :

    List<Filter_IDs> filterids = ef.filterLine.Select(o => new { objectType = o.objectType, object_id=o.object_id})
        .GroupBy(fl => fl.objectType).ToList()
        .Select(fl => new Filter_IDs { type = fl.Key, objects = fl.Select(x => x.object_id).ToList() })
        .ToList();