GONeale
GONeale

Reputation: 26484

Unexpected - Cannot compare elements of type 'System.Int32[]'. Only primitive types, enumeration types and entity types are supported

Any ideas what the problem might be here on an EF DbContext query? As far as I have understood, this should work according to a fellow SO poster.

I've tried Lists, null, not null checks, to no avail. The query does work however, if I remove the null check and just leave the Contains(). However, it is a requirement to return all records if testIDs is null.

var testIDs = new int[] { 1, 3 };
var test = session.All<VendorBooking>(x => testIDs == null || testIDs.Contains(x.VendorServiceID)).ToList();

(session.All simply utilises context.Set<T>.Where())

Exception thrown: 'System.NotSupportedException' in EntityFramework.SqlServer.dll

Additional information: Cannot compare elements of type 'System.Int32[]'. Only primitive types, enumeration types and entity types are supported.

enter image description here

Many thanks

Upvotes: 5

Views: 5004

Answers (4)

sasan
sasan

Reputation: 111

You can try this :

var testIDs = new int[] { 1, 3 };
var test = session.All<VendorBooking>(x => !testIDs.Any() || 
testIDs.Contains(x.VendorServiceID)).ToList();

Upvotes: -1

Av.Raj
Av.Raj

Reputation: 65

    var test = session.All<VendorBooking>(x => testIDs.Contains()==0 || 
    testIDs.Contains(x.VendorServiceID)).ToList();

This is normally working. Don't get confused by the OR operator so only one condition must be true for the full expression to be true. testIDs.Contains(x.VendorServiceID) evaluates to true when any value was passed to testIDs, otherwise testIDs.Contains()==0 is true when null was passed.

Upvotes: 0

Richard Schneider
Richard Schneider

Reputation: 35477

testIds cannot be null, so try this

var testIDs = new int[] { 1, 3 };
var test = session
   .All<VendorBooking>(x => testIDs.Contains(x.VendorServiceID))
   .ToList();

Revised

var results = (testIds == null || testIds.Length == 0)
  ? session.All<VendorBooking>()
  : session.All<VendorBooking>(x => testIDs.Contains(x.VendorServiceID));
var test = results.ToList();

Upvotes: 0

Backs
Backs

Reputation: 24913

Something like this maybe. Also, you can extract common parts and make it shorter.

var testIDs = new int[] { 1, 3 };
if (testIDs == null)
{
    var test = session.All<VendorBooking>()
        .ToList();
}
else
{
    var test = session.All<VendorBooking>(x => testIDs.Contains(x.VendorServiceID))
       .ToList();
}

Upvotes: 5

Related Questions