How IEnumerable<T> interface has ToList() Method - linq

My Code:
internal DbSet<TEntity> DbSet;
public virtual IEnumerable<TEntity> Get()
{
IQueryable<TEntity> query = DbSet;
return query.ToList();
}
As you can see above we are calling ToList() method. When I go into IQueryable, I have seen that it gets inheritence from IEnumerable but in IEnumerable I can not see any ToList() method. Where and how this method comes from? Can you help me please.

The extension methods provided for IQueryable<T> and IEnumerable<T> are generally respectively found in the types Queryable and Enumerable.
Keep in mind that the former are interfaces. Interfaces can't have implementations defined. These are extension methods (with implementation) which means they need to be defined in a static class as static methods.
Queryable [MSDN]
Enumerable [MSDN]
Extension Methods [MSDN]

Related

How to use linq extensions with Func parameters in Dynamic Linq expressions?

While somewhat powerful, the System.Linq.Dynamic library has a surprising lack of documentation, especially in regards to what conventions must be followed for more complex queries.
In a query I'm working on, it contains a FirstOrDefault call, but I can't seem to get it to work.
Here's the whole (unworking) expression:
"Locations.FirstOrDefault(x => x.IsPrimaryLocation).Address1 as Address"
Can I write this FirstOrDefault expression to work with Dynamic linq?
What is the correct way to write this expression?
Extending the dynamic library is certainly an option as already suggested.
an alternative given the Where in Dynamic Linq returns an Iqueryable
public static class DynamicQueryable {
public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values) { return (IQueryable<T>) Where((IQueryable) source, predicate, values); }
public static IQueryable Where(this IQueryable source, string predicate, params object[] values) {
using a DYnamic Object for the context or repository "locations".
Then use a where which could contain dynamic string predicate and follow with firstOrDefault.
(catch or test for null not considered)
DynamicLocations.Where(x => x.IsPrimaryLocation).FirstOrDefault( ).Address1 as Address;
or dynamic where if needed
DynamicLocations.Where("IsPrimaryLocation",new string[]).FirstOrDefault( ).Address1 as Address;
Details:
You can expose on a method on a generic repository Class which you instantiate as a dynamic
public virtual IQueryable<TPoco> DynamicWhere(string predicate, params object[] values) {
return AllQ().Where(predicate, values);
}
Dynamic Generic Repository instantiation Sample
public class RepositoryFactory<TPoco> where TPoco : BaseObject,new() {
public IRepositoryBase<TPoco> GetRepository(DbContext context) {
// get the Pocotype for generic repository instantiation
var pocoTypes = new[] {typeof (TPoco)}; // but supports <T,U>
Type repBaseType = typeof (RepositoryBase<>);
IRepositoryBase<TPoco> repository = InstantiateRepository(context, repBaseType, pocoTypes);
return repository;
}
private IRepositoryBase<TPoco> InstantiateRepository(DbContext context, Type repType, params Type[] args) {
Type repGenericType = repType.MakeGenericType(args);
object repInstance = Activator.CreateInstance(repGenericType, context);
return (IRepositoryBase<TPoco>)repInstance;
}
}

How to tell, in VS2010, that a class needs to be disposed?

Is there an easy way, in Visual Studio 2010, to know if a type needs to be disposed?
e.g. i write code:
Collection<Prize> prizes = new Collection<Prize>();
i don't know if i need to call dispose.
The way i handle it now is click on Collection and press F12, looking for IDisposable:
public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
then i recursively descend into each class, looking to see if any implement IDisposable:
public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
public interface ICollection<T> : IEnumerable<T>, IEnumerable
public interface IEnumerable<T> : IEnumerable
public interface IEnumerable
public interface IEnumerable
public interface IEnumerable<T> : IEnumerable
public interface IEnumerable
...
Note: Don't confuse the example with the question. i might have the code:
SqlConnection conn = new SqlConnection();
where i then recusively iterate into ancestor types:
public sealed class SqlConnection : DbConnection, ICloneable
public abstract class DbConnection : Component, IDbConnection, IDisposable
So i've found that this class needs me to call Dispose. But it would be easier if i didn't have to F12 descend into stuff
If you have the premium or ultimate edition code analysis rule CA1001:Types that own disposable fields should be disposable will find types that need to be disposed. To enable code analysis go to the project properties and select the code analysis tab, select Enable Code Analysis on Build, the Microsoft.Design ruleset must be included for the CA1001 rule to run.
Coderush from Devexpress includes similar functionality. This is the only option for the standard edition. There may other add-ins that offer similar functionality.
This cannot be done in the express edition.

Compiled Linq with Generic Repository Design Pattern

I've been looking around the web but I've yet to found any information on this. As we know Linq gives us CompiledQuery which transform the expression into T-SQL before running it. I'm trying to design a generic repository to interact with my EF but with the exception the Linq queries is compiled. If anyone could shead some light on this that would be great :)
It is hardly possible because if you want to pre-compile query you must know it. With generic repository you usually have only this:
public interface IRepository<T>
{
IQueryable<T> GetQuery();
}
So the code using a repository instance is responsible for defining the query. Pre-compilation requires concrete repository which will contain methods like:
IEnumerable<Order> GetOrdersWithHeaderAndItemsByDate(DateTime date, int take, int skip);
IEnumerable<OrderHeader> GetOrderHeadersOrderedByCustomer(int take, int skip);
etc.
Obviously you can hardly prepare such queries in generic repository beacuse they are dependent on concrete entity.
You are looking for an implementation of the Specification pattern. Basically, this is creating a Specification object that contains the information needed to filter your query. By using Specifications, you can have a Generic Repository implementation, and put your custom query logic in the specification. The specification base class looks something like:
public class Specification<TEntity>
{
public Specification(Expression<Func<TEntity, bool>> predicate)
{
_predicate = predicate;
}
public bool IsSatisfiedBy(TEntity entity)
{
return _predicate.Compile().Invoke(entity);
}
public Expression<Func<TEntity,bool>> PredicateExpression{
get{ return _predicate; }
}
private Expression<Func<TEntity, bool>> _predicate;
}
A very helpful article about implementing the specification pattern with the Entity Framework can be found at http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/

Need help trying to EagerLoad some data in EntityFramework

I'm trying to do some eager loading on an EF Entity.
so, if the entity is called Orders .. then I guess i would do the following...
_someContext.Orders.Include("Whatever") ....
But the problem is, I have a method like the following ...
public IQueryable<Order> Find(Expression<Func<Order, bool>> predicate)
{
return CurrentContext.Orders.Where(predicate);
}
which works great .. but can i leverage the Expression predicate to include the Include("whatever") in there, instead of having to add another method parameter?
I don't think so. Since the predicate and ObjectQuery.Where Method in genral has nothing to do with eager loading by Include. You can create a extension method though, but that does not save you from having yet another parameter for specifying the include:
public IQueryable<Order> Find(Expression<Func> predicate, string include) {
return CurrentContext.Orders.Where(predicate, include);
}
public static ObjectQuery<T> Where<T>(this ObjectQuery<T> entity, Expression<Func<T, bool>> predicate, string include) {
return (ObjectQuery<T>)entity.Include(include).Where<T>(predicate);
}

How do you transfer the execution of a Expression created by an IQueryable object to a IEnumerable?

In my code I'd like to make my repositories IQueryable. This way, the criteria for selection will be a linq expression tree.
Now if I want to mock my repository in theorie this is very easy : just implement the interface of my repository (which is also a IQueryable object).
My mock repository implementation would be only a in memory collection, but my question is : Do you know an easy way to implement the IQueryable interface of my mock, to transfer the query to my in-memory collection (IEnumerable) ?
Thanks for your response,
Some precision
The client object of my repository will use my repository this way :
var result = from entry in MyRepository where entry.Product == "SomeProduct" select entry;
What does ToList or AsEnumerable is to execute the query and return the result as a List or as a IEnumerable. But I have to implement the IQueryable interface on my repository, with a IQueryProvider which transform the expression in a call to a IEnumerable object.
Solution
The implementation of the solution is delegating call to IQueryable to my inmemory collection with AsQueryable.
public class MockRepository : IQueryable<DomainObject>
{
private List<DomainObject> inMemoryList = new List<DomainObject>();
#region IEnumerable<DomainObject> Members
public IEnumerator<DomainObject> GetEnumerator()
{
return inMemoryList.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return inMemoryList.GetEnumerator();
}
#endregion
#region IQueryable Members
public Type ElementType
{
get
{
return inMemoryList.AsQueryable().ElementType;
}
}
public Expression Expression
{
get
{
return inMemoryList.AsQueryable().Expression;
}
}
public IQueryProvider Provider
{
get
{
return inMemoryList.AsQueryable().Provider;
}
}
#endregion
}
Use AsQueryable on your mocks. Now they're queryable and you can treat them like any other queryable.
Can you use the extension method
.ToList<>

Resources