LINQ query with GroupBy causing "Unable to create a constant value of type 'System.Object'..."

StackOverflow https://stackoverflow.com/questions/19412052

  •  01-07-2022
  •  | 
  •  

Question

I tried searching on this, but can't seem to find anything that matches my LINQ query to use to help me figure this one out.

I'm getting a message in the debugger in the Results View->base object

+base {"Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context."} System.SystemException {System.NotSupportedException}

Here is my LINQ query (that returns a result fine in LINQPad...):

public IEnumerable<PendingItems> GetHazmatPendingShipping()
{
    var pending = context.HazmatInfoes
                         .Where(h => (h.ShippingFlag.Equals(false) && (h.ShippingType.Equals("Manual"))))
                         .GroupBy(x => new {x.ToBU, x.FromBU}, y => new {y})
                         .Select(p => p);
    return pending;
}

I know my return type is wrong. Will work on that after I figure out why this query fails to return a result.

My answer to this problem:

Since I had a key that was composite {string, string}, I had to create a class called PendingItems.

public IQueryable<PendingItems> GetHazmatPendingShipping()
    {
        IQueryable<PendingItems> pending = context.HazmatInfoes
            .Where(h => ((h.ShippingFlag.Value == false && h.ShippingType.Equals("Manual"))))
            .GroupBy(x => new {x.ToBU, x.FromBU}, y => y)
            .Select(p => new PendingItems {ToBu = p.Key.ToBU, FromBu = p.Key.FromBU, Items = p});
        return pending;
    }

The PendingItems class:

using System.Collections;
using System.Collections.Generic;

namespace Hazmat.Models
{
    public class PendingItems : IEnumerable
    {
        public string ToBu { get; set; }
        public string FromBu { get; set; }
        public IEnumerable<HazmatInfo> Items { get; set; }

        public IEnumerator GetEnumerator()
        {
            yield return this.Items;           
        }
    }
}

Thanks, Tim

P.S. This answer helped with this problem: https://stackoverflow.com/a/1775514/2733668

Was it helpful?

Solution

This error occurs when there is condition regarding Nullable<> field, and comparison doesn't reflect that. Then primitive (false in your case) is converted to Nullable<> object, and exception is raised.

Probably ShippingFlag is of type Nullable<bool>, and assuming that you should rewrite your condition like this:

var pending = context.HazmatInfoes
    .Where(h => (!h.ShippingFlag.HasValue && h.ShippingFlag.Value.Equals(false)) && h.ShippingType.Equals("Manual"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top