1

I would like to implement IdbSet to provide my DbContext a custom implementation that will essentially serve to filter my data for the currently logged in user (I am working on a multi-tenant application). The general idea I am going with is very similar to this post: Can a DbContext enforce a filter policy?

However, it is not clear to me how to make DbContext "know" about how to use my own class that implements IDbSet. I am having a tough time finding documentation on this. Any pointers would be helpful!

TIA, -jle

Community
  • 1
  • 1
jle
  • 432
  • 1
  • 5
  • 11

1 Answers1

1

I'm almost sure that you cannot create your own implementation of IDbSet and pass it to entity framework. Such implementation will lose all stuff related to EF which is internally implemented in DbSet itself - by internally I really mean that there is no public API to replace it. IDbSet interface is provided not because it is supposed to create your own sets but because it allows mocking sets when unit testing application. The only way you can extend functionality is either:

  • Inheriting DbSet but I'm afraid that it will not help you as well because methods / properties will not be marked as virtual.
  • Creating custom IDbSet implementation which will wrap DbSet. This looks like the best chance but you can still find that DbContext doesn't like your new implementation. I gave this very quick try but I was not successful. My implementation worked for persisting but not for querying.
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Thanks Ladislav. I misunderstood the intent behind/current capabilities of DbContext and IDbSet. I will be looking for another way to implement multi-tenancy in my application. Thanks again for your help! – jle Jun 05 '11 at 13:38
  • 1
    You can always wrap your data access and add `Where` condition in the wrapper. – Ladislav Mrnka Jun 05 '11 at 13:43
  • @LadislavMrnka what about Extension methods for DbSet? is this good idea? – AminM Jul 01 '18 at 03:47