简体   繁体   中英

LINQ error: System.NotSupportedException on GroupBy Selection

When var items = q3.ToList(); executes from the code snippet below, it throws exception System.NotSupportedException. The aim is to get the list of items after the grouping.

Exception: Unable to create a constant value of type 'AppDB.Stage.Rules'. Only primitive types or enumeration types are supported in this context. Unable to create a constant value of type 'AppDB.Stage.Rules'. Only primitive types or enumeration types are supported in this context.

  var valuations = context.stage
                .Where(q => q.stageID == stageID && !rules.ToList().Any(r => r.type1 == q.type1 || r.type2 == q.type2))
               .GroupBy(q => q.stageKey)
               .Select(g => g) ;

            var q3 = valuations.Select(y => new StageType
            {
                TypeKey = y.Key,
                TypeName= "UNKNOWN",
            });
            var items = q3.ToList(); //error here

Your database doesn't have any idea of what your in-memory rules actually is, and in-turn cant convert this statement to SQL

The simplest solution will be to leave it as an IQueriable and don't use ToList ,

context.stage
       .Where(q => q.stageID == stageID && !rules.Any(r => r.type1 == q.type1 || r.type2 == q.type2))
       .GroupBy(q => q.stageKey)
       .Select(g => g) ;

However , if it is already in memory, then you will have to send the values as a primitive list

var type1s = rules.Select(x => x.type1);
var type2s = rules.Select(x => x.type2);

context.stage
       .Where(q => q.stageID == stageID && !type1s.Contains(q.type1) && !type2s.Contains(q.type2))
       .GroupBy(q => q.stageKey)
       .Select(g => g) ;

Because rules.ToList() makes results in memory, you can't use it inside an IQueriable that executes over SQL. You should first bring your data into memory and then narrow it by other in-memory object.

 var valuations = context.stage.ToList()
                .Where(q => q.stageID == stageID && !rules.ToList().Any(r => r.type1 == q.type1 || r.type2 == q.type2))
               .GroupBy(q => q.stageKey)
               .Select(g => g) ;

            var q3 = valuations.Select(y => new StageType
            {
                TypeKey = y.Key,
                TypeName= "UNKNOWN",
            });
            var items = q3.ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM