问题
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
回答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 asvirtual
. - Creating custom
IDbSet
implementation which will wrapDbSet
. This looks like the best chance but you can still find thatDbContext
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.
来源:https://stackoverflow.com/questions/6227461/entity-framework-implementing-idbset