0

When using an EF ObjectContext I see two different extensions methods with the same signature as consecutive choices. It doesn't makes sense to me that there would be some magic that caused one or the other to get called based on which one I picked, so what is actually going on?

enter image description here

reuben
  • 3,360
  • 23
  • 28
Aaron Anodide
  • 16,906
  • 15
  • 62
  • 121

1 Answers1

5

I'm assuming that Campaigns is an instance of DbSet<Campaign>? DbSet inherits DbQuery, which implements IOrderedQueryable, the definition for which is:

public interface IOrderedQueryable<out T> : IQueryable<T>, 
    IEnumerable<T>, IOrderedQueryable, IQueryable, IEnumerable

As you can see, both IQueryable<T> and IEnumerable<T> are implemented, but the definition of IQueryable shows that it extends IEnumerable:

public interface IQueryable : IEnumerable

So basically, the extension method is implemented for IEnumerable, but it's also available from IQueryable as it extends the original interface. Intellisense is picking up both of these options because you could end up implicitly or explicitly casting the type to an IEnumerable.

The method that will actually be run will depend on the type on which it's called. For example, on your Campaigns instance of DbSet<Campaign> the method will translate it (if you're using MS SQL) into a SELECT TOP 1... query, but if you're calling it on Campaigns.ToList(), which is IEnumerable, it'll return the item at the zero index. The implementation of the extension methods are different for each type.

Hope that makes sense :)

greg84
  • 7,541
  • 3
  • 36
  • 45
  • yes, that makes sense, thank you (it's ObjectSet but I bet your answer is right nonetheless) – Aaron Anodide Jul 07 '12 at 23:22
  • Ah ok, `ObjectSet` implements `IEnumerable` and `IQueryable` directly, so it's pretty much the same, just ignore the first paragraph and `IOrderedQueryable` definition. See http://msdn.microsoft.com/en-us/library/dd412719.aspx – greg84 Jul 07 '12 at 23:25
  • This also might be a useful read: http://stackoverflow.com/questions/252785/what-is-the-difference-between-iqueryablet-and-ienumerablet – greg84 Jul 07 '12 at 23:26