rgvlee/EntityFrameworkCore.Testing

DbContext IQueryable returns null

Closed this issue · 2 comments

I have a DbContext implemented as follows:

public class DomainContext : DbContext
{
public virtual DbSet<User> AllUsers { get; set; }
[NotMapped] public virtual IQueryable<User> Users => AllUsers.Where(x => !x.Deleted);
}

Which is then utilized by AutoFixture:

var dbContextOptions = new DbContextOptionsBuilder<DomainContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
var mockedDbContext = Create.MockedDbContextFor<DomainContext>(dbContextOptions);
fixture.Register<DomainContext>(() => mockedDbContext);

AllUsers is populating correctly, however Users is returning null.

Users is returning null as EntityFrameworkCore.Testing doesn't know how to set it up. It'll look for and set up a db set. But it won't look for a custom IQueryable<T> property.

Is there any reason you are marking Users virtual? As we are mocking an implementation e.g., a partial mock, Moq will use the implementation for a non virtual members. That would then access the AllUsers db set which should prompt EntityFrameworkCore.Testing to set it up if it hasn't done so already.

Thanks! Good pick up. Users was virtual for legacy reasons - making in non-virtual resolved the issue and it populates correctly now. Thanks again.