当没有找到结果时,Iqueryable抛出异常

时间:2014-06-07 05:52:38

标签: entity-framework iqueryable

从我所看到的代码中,我找到的代码不应该在没有找到结果时抛出异常。我使用的通用存储库类似于此处的内容: http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/

抛出异常的代码:

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

有没有人有这方面的经验或知道在运行查询时会引发异常的原因?

更新

查找代码:

        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);
    }

1 个答案:

答案 0 :(得分:2)

你在空对象上调用ToList()

请参阅以下文章以处理空列表

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