Dru
Dru

Reputation: 357

Iqueryable throws exception when no results found

From what I have read the code I have should not be throwing an exception when no results are found. I am using a generic repository similar to what is found here: http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/

The code where the exception is thrown:

List<CADDrawing> projectDrawings = repository.Find<CADDrawing>(x => x.ProjectNumber == result.StringResult)
                .Where(y => y.Obsolete == false)
                .ToList();

Does anyone have experience with this or know what would cause an exception to be thrown when running a query?

Update:

The find code:

        public IEnumerable<TEntity> Find<TEntity>(ISpecification<TEntity> criteria) where TEntity : class
    {
        return criteria.SatisfyingEntitiesFrom(GetQuery<TEntity>()).AsEnumerable();
    }

        public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
    {
        /* 
         * From CTP4, I could always safely call this to return an IQueryable on DbContext 
         * then performed any with it without any problem:
         */
        // return DbContext.Set<TEntity>();

        /*
         * but with 4.1 release, when I call GetQuery<TEntity>().AsEnumerable(), there is an exception:
         * ... System.ObjectDisposedException : The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
         */

        // here is a work around: 
        // - cast DbContext to IObjectContextAdapter then get ObjectContext from it
        // - call CreateQuery<TEntity>(entityName) method on the ObjectContext
        // - perform querying on the returning IQueryable, and it works!
        var entityName = GetEntityName<TEntity>();

        IQueryable<TEntity> ThisQuery = ((IObjectContextAdapter)DbContext).ObjectContext.CreateQuery<TEntity>(entityName);
        System.Data.Entity.Core.Objects.ObjectQuery objectQuery = (System.Data.Entity.Core.Objects.ObjectQuery)ThisQuery;
        objectQuery.MergeOption = System.Data.Entity.Core.Objects.MergeOption.OverwriteChanges;

        return ThisQuery;
    }


    public IQueryable<TEntity> SatisfyingEntitiesFrom(IQueryable<TEntity> query)
    {
        return query.Where(Predicate);
    }

Upvotes: 0

Views: 1239

Answers (1)

3dd
3dd

Reputation: 2540

You're calling ToList() on a null object

Please see the following post for handling of null lists

how do I treat null lists like empty lists in linq?

Upvotes: 2

Related Questions