Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Linq - Comparing Nullable objects - NotSupportedException

I need to compare an object with a parameter that I'm passing in. The logic being:

  • If territory == null. Return all Orders
  • If territory != null and the Territory entity from Orders is != null. Return Orders matching on the Id property (PK) of both entities.

I have the following LINQ statement:

The cut down version of my method is (there are normally other filters in the WHERE clause):

  public void Execute(Territory territory)
  {
    using (var context = DatabaseHelper.CreateContext())
    {
      var orders = context.Orders.Where(x =>
        (
          (territory == null) ||
          (x.Territory != null && x.Territory.Id == territory.Id)
          )
        );

      if (!orders.Any()) //Exception occurs here on materialising the query
      {
        //Do something
      }
    }
  }

I receive the exception NotSupportedException and the message:

Unable to create a constant value of type 'ENTITY'. Only primitive types or enumeration types are supported in this context.

Whilst I understand the error as I'm not passing in a primitive type. How can I change the LINQ query so it returns the expected results?

like image 814
JBond Avatar asked Aug 11 '26 19:08

JBond


1 Answers

Try this:

var t = territory == null;
var orders = context.Orders.Where(x =>        
       t || (x.Territory != null && x.Territory.Id == territory.Id));

The reason behind this is it tries to translate territory into a constant in SQL query but of course territory is not primitive or any equivalent type on server, so it throws the exception. You can however cache a constant boolean outside (but still in the effective scope of checking territory) and use that constant in the query.

like image 141
Hopeless Avatar answered Aug 13 '26 07:08

Hopeless



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!