So, I have a whole system built as microservices.On a service level, I'm utilizing Hexagonal Architecture with lightweight DDD (no events, aggregators etc.)

I have a service that fetches Users via their Tokens, and then I have to fetch their Permissions accordingly.

I'm trying to figure out how to fetch data via EF, without leaking the implementation details to the domain layer.

Approach A: enter image description here

This allows me to lazyload Permissions onto Users after running the method, but since whole logic is contained in the domain - I'm leaking the implementation (usage of IQueryable).

Approach B: enter image description here

This also leaks implementation, because I'm restricting domain to EF - If I used an in-memory database instead of EF - I wouldn't need this solution, and thus it's a bad solution.

Approach C: enter image description here

This is the only solution that doesn't leak anything and allows me to easily plug the repository out of EF, and plug a text file, an in-memory database or anything really.

The only issue is - it eager-loads data, which will become a huge query if I use this approach for stuff like: Posts, Comments etc.

I'm clueless at this point, is there a 4th option?

  • 2
    Take off the ToList() call and it shouldn't eager load anymore. Dec 5, 2021 at 17:08
  • @RobertHarvey Yeah, it won't load at all - it'll be an empty list of Permissions and I need that data
    – JTinkers
    Dec 5, 2021 at 17:23
  • 1
    Well, that's odd. Have you tried calling ToList() on the result of the GetUsersByTokens call? Dec 5, 2021 at 17:24
  • 2
    Uh, no. ToList merely compels the query to execute. It's just a test. Remember, this is supposed to be a lazy query, so if you look at the output without enumerating it, you won't see anything. Dec 5, 2021 at 17:26
  • 1
    Well, the ToList in your implementation guarantees that the query will be eager loaded. Dec 5, 2021 at 17:31

1 Answer 1


The simplest way to use lazy-loading is by installing the Microsoft.EntityFrameworkCore.Proxies package and enabling it with a call to UseLazyLoadingProxies.

For example:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder

Or when using AddDbContext:

    b => b.UseLazyLoadingProxies()


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.