1

I have this Moq setup:

_mockContext.Setup(x => x.CarSections).Returns(new List<CarSection> { _carSection }.ToDbSet());

Which basically assigns the List to the entity of DbContext.CarSections.

One of the methods is an async method. Something like:

public async Task<CarSection> GetSectionAsync(int sectionId)
    {
        return await _context
            .CarSections
            .FirstOrDefaultAsync(s => s.CarSectionId == sectionId && s.StatusCode == 4);
    }

When it goes through that method I'm getting the error:

The provider for the source IQueryable doesn't implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations.

Which I believe is because of the .ToDbSet(). Already tried with Task.FromResult(new List<CarSection>{ _carSection } but the .Returns expects a "DbSet" and not a "Task".

Any ideas on how to workaround this?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
mrbitzilla
  • 368
  • 3
  • 11
  • No clue where ToDbSet is from, but assuming it's setting up a Mock, you'd need to add mock.As() followed by setup of the methods on that interface. Perhaps this answer to this question helps https://stackoverflow.com/a/43594599/491907 – pinkfloydx33 May 25 '20 at 23:36

1 Answers1

2

It would seem that the .ToDbSet() extension (what package is this extension from?) doesn't setup the IQueryable<T>.Provider property with a provider that implements IDbAsyncQueryProvider.

How would I resolve this?

  • Look for a mocking library that will do this for you. I moved to EFCore a fair while ago and so I am not sure what the landscape currently looks like for EF, possibly Effort?

  • If you want to roll your own check out the doco from MS which provides a ready to go copy/paste Moq implementation. There's a bit of scaffolding involved but MS has done the hard work for you. You'll end up creating your own implementation of IDbAsyncQueryProvider and using that as the provider for your DbSet<T>.

rgvlee
  • 2,773
  • 1
  • 13
  • 20
  • 1
    This what I ended up doing at the end. Works perfectly, thanks. – mrbitzilla Jun 02 '20 at 15:01
  • Hi , Can I know how you solve this question? @rmed1na –  Apr 08 '22 at 16:04
  • @JiriumJ sure, I ended doing the thing on the second bullet point of this answer. Just copy/paste the implementation MS provides on their website. So far, has been working fine with no need to tweak anything since then. – mrbitzilla Nov 30 '22 at 03:53