Question

I recently, out of ignorance and lack of time, merged the domain models (POCO entity classes) from several projects into one 'DataModel' project, because I didn't want to duplicate dedicated DbContexts over all the projects. It struck me as ideal that something generic might be done, like a DbContext extension, to which one can add DbSet instances from various client projects.

I have read mention of such things, normally in the same circles as authors that contend - and I agree wholeheartedly - that the repository functionality is fulfilled completey by the DbSet class.

Can anyone offer any advice for building a generic DbContext which can exist in one project, where other projects can all have their domain models (sets of domain entities) registered with the shared DbContext, where they are all allocated they own DbSet to act as their repository?

Was it helpful?

Solution

building a generic DbContext which can exist in one project, where other projects can all have their domain models (sets of domain entities) registered

Interesting idea, but I'm not sure what you would gain by that.

For one, you'd never be able to simply type db.Customer (or similar). It should always be genericdb.Set<Customer>(), not knowing whether genericdb knows about Customer at all. (It may not have been registered).

Then, how should this registering take place? There are two ways to let a context map a class to a database model:

  1. Creating a DbSet property in a DbContext-derived class and rely on code-first default conventions concerning table and column names, pluralization, etc.
  2. Providing mapping configuration.

The first option defeats the purpose of a generic context class, so you'd have to register the domain classes by supplying EntityTypeConfiguration<T>s for each class in the domain, also for classes that normally could do without. (This should be done in the context's constructor, by the way.)

A further implication would be that somewhere you'd need a component/service that knows which groups of classes belong together and is able to deliver a coherent list of configurations. So, in stead of having dedicated contexts as an organizing principle out of the box you'd have to create your own organizer.

But back to the start. Couldn't you create a DAL that contains a DbContext factory that supplies the contexts as they previously existed for your projects? You don't have to duplicate dedicated DbContext classes this way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top