سؤال

I have this method:

protected async Task<List<T>> Get<T>(Expression<Func<T, bool>> select) where T : class, IEntity
{
    var query = Context.Set<T>();
    query = query.Where(select);
    return await query.ToListAsync<T>();
}

And I call it like this:

var result = await Get<T>(a => a.Id == myId);

But the Get method keeps throwing 'Value cannot be null. Parameter: source'.

What am I missing?

Update 1:
StackTrace: at System.Data.Entity.Utilities.Check.NotNull[T](T value, String parameterName) at System.Data.Entity.QueryableExtensions.ToListAsync[TSource](IQueryable'1 source) at SoccerPool.MVC5.Models.Config.BaseApiController.<Get>d__49'1.MoveNext() in c:\Projects\SoccerPool\SoccerPool.MVC5\Models\Config\BaseApiController.cs:line 190

Update 2:
Context.Set<T>() is not null. It contains 48 records if I don't perform the linq query. And 'Context' is a property which returns an instance of my DbContext.

هل كانت مفيدة؟

المحلول

Context.Set is probably null.

Also, please do a test with synchronous code rather than async, maybe the issue is in premature ressource disposing.

Please provide full stacktrace to get sure, and explain us how works your datacontext (Get method).

نصائح أخرى

I tricked you guys, apparently. My sincerest apologies.

After creating a sync version which Richard suggested I noticed 'query' in that method to be null. So the exception made sense.

In trying to clarify the code for SO I removed the following (among other stuff):

protected async Task<List<T>> Get<T>(
    Expression<Func<T, bool>> select) where T : class, IEntity
{
    var query = Context.Set<T>() as DbSet<T>;
    query = query.Where(select) as DbSet<T>;
    return await query.ToListAsync<T>();
}

Notice the 'as DbSet'. This worked fine for the Context.Set but not for the '.Where' which returns an IQueryable which, my reasons unknown to me, is not castable to a DbSet. (I thought it inherited from IQueryable).

So the 'as DbSet' made query null and thereby wasting all of your time.

Thank you for indulging me anyway.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top