Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If IQueryable<T> inherits IEnumerable<T> , how come IQueryable<T> is LINQ to SQL?

IEnumerable<T> case is LINQ-to-object and IQueryable<T> is the interface that allows LINQ-to-SQL , however IQueryable<T> inherits IEnumerable<T> , so how is it possible to IQueryable<T> to filter rows in the Database while IEnumerable<T> filters objects in the memory ?

like image 998
JAN Avatar asked Dec 19 '22 08:12

JAN


2 Answers

You are mistaking inheritance and interface implementation.

IQueryable<T> inherits IEnumerable<T> but that is radically different from inheritance between classes where the derived class inherits the implementation of the base class. Interfaces are simply contracts, there is no actual code behind them:

public interface IFoo
{
    void Foo(); //its simply a contract, no implementation at all.
}

public interface IBar: IFoo
{
    void Bar();
}

public class Foo: IFoo
{
    void Foo() { //Foo's sepecific implementation goes here }
}

public class Bar : IBar 
{
    void Foo() { //Bar's specific implementation goes here }
    void Bar() { //implementation goes here }
}

The fact that Bar implements IFoo through IBar doesn't mean, in any way, that there is any relationship whatsoever between Foo and Bar.

like image 50
InBetween Avatar answered Dec 20 '22 21:12

InBetween


how is it possible to IQueryable to filter rows in the Database while IEnumerable filters objects in the memory ?

They don't, that is an inaccurate statement.

The actual implementation code is inside extension methods which are selective for either IEnumerable or IQueryable.

In EF there is a

Where<T>(this IQueryable<T>, Expression<Predicate<T>> )

and in System.Linq there is

Where<T>(this IEnumerable<T>, Predicate<T>)

The resoluton rules will prefer an IQueryable extension over the basic Linq one, and the magic is enabled through the Expression<> parameter.

like image 35
Henk Holterman Avatar answered Dec 20 '22 21:12

Henk Holterman