Ambiguous Invocation IQueryable or IEnumerable

entity-framework linq

Question

I instantiated a context and want to write a simple query:

var result = db.Set.Where(x => x.Id == num).Select(whatever);

and I can't get rid of the red squiggly under Where complaining about an ambiguous invocation between System.Collections.Generic.IEnumerable and System.Linq.IQueryable. System.Linq is specifically referenced, and System.Collections.Generic is not referenced anywhere in the project. How can I tell the code that I want to use System.Linq.IQueryable?

1
29
3/16/2019 6:00:13 AM

Accepted Answer

Got it. People don't seem to like this answer, but it solved the problem I described in the question.

db.Set.AsQueryable().Where(...
0
1/30/2015 8:03:32 PM

Popular Answer

This problem is normally caused by a failure in type inference from in the expression provided to the Where statement. As was mentioned in the comments above it is 100% caused by the assignment operator in the lambda returning an int instead of a bool.

To be clear - where you have

var result = db.Set.Where(x => x.Id = num).Select(whatever);

You should have

var result = db.Set.Where(x => x.Id == num).Select(whatever);

Another good (and more common) example of this is something like this

public class Elem 
{
    public bool IsSomething {get;set;}                    
    public bool? IsSomethingElse {get;set;}
}

Then if you do the following query, which looks very reasonable at fist glance, it will fail to compile with the rather puzzling error of "abiguous invocation"

IQueryable<Elem> queryable = GetQueryable();
var result = queryable.Where(e => e.IsSomething && e.IsSomethingElse).ToList();

If you weren't writing this statement inside a lambda then you would get a more meaningful error of

"Cannot apply operator '&&' to operands of type 'System.Nullable<bool>' and 'bool'"

Which would immediately tell you that you are failing to return a boolean.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow