Michael
Michael

Reputation: 13636

Why I get error on my query?

I use entity framework 6.

I have this array:

int?[] regionTypeId = [1,2,3];

In this query (linq to query):

    var t = (from sites in context.Set<Site>()
             where regionTypeId.Contains(sites.Regions.Select(x=>x.RegionTypeId).ToList())

            select sites).AsNoTracking<Site>();

I get this error:

Error 15 'int?[]' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.ParallelEnumerable.Contains<TSource>(System.Linq.ParallelQuery<TSource>, TSource)' has some invalid arguments    

Any idea how to fix it?

Upvotes: 0

Views: 141

Answers (5)

Gert Arnold
Gert Arnold

Reputation: 109255

Tinwor was the only one to spot that you don't execute the expected ...

regionTypeId.Contains(someInteger)

... but ...

regionTypeId.Contains(some IEnumerable<int>)

... which obviously is the wrong parameter. But he didn't show the correct alternative, which is

var t = from site in context.Set<Site>().AsNoTracking()
        where site.Regions.Any(x => regionTypeId.Contains(x.RegionTypeId))
        select site;

This checks if a site has at least one Region whose RegionTypeId is in regionTypeId.

Upvotes: 0

Igor
Igor

Reputation: 62268

int[] regionTypeId = new int[] {1,2,3};

var t = (from sites in context.Set<Site>()
    where regionTypeId.Contains(sites.Regions.Select(x=>x.RegionTypeId))
    select sites).AsNoTracking<Site>();
  1. Fixed your array of ints.
  2. Removde the ToList, the contains block will be evaluated on the database server.

Upvotes: 0

mybirthname
mybirthname

Reputation: 18127

You are getting this error because you are trying to execute int?[].Containts(List<int>). Specify your whole error next time.

'int?[]' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains>(IQueryable>, List)' requires a receiver of type 'IQueryable>'

Why not just make your int?[] to int[] and use it in linq.

 var result = regionTypeId.Where(x => x != null).Cast<int>().ToArray();

And after that your linq:

  var t = (from sites in context.Set<Site>()
         where result.Contains(sites.Regions.Select(x=>x.RegionTypeId).ToList())

        select sites).AsNoTracking<Site>();

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29036

The problem is with your declaration, The following code works fine for me :

int someValue=1;
int?[] regionTypeId =  { 1, 2, 3 };
if (regionTypeId.Contains(someValue))
{
   // code here
}

Upvotes: 1

Tinwor
Tinwor

Reputation: 7983

The extension method Contains(this IEnumerable<int?> source, int value?):bool doesn't accept a List<int> or List<int?> but in this case accept only an Nullable int aka int?

Upvotes: 1

Related Questions