Is having two dbContext for the same Connection string considered bad practice?

Asked

Viewed 173 times

2

I initially had a DbContext with all the DbSets of my entities. However, I needed to create a DbContext<T> who owns a DbSet generic for methods that are properly generic. It turns out that the two Dbcontext points to the same connectionstring. Can the existence of both in a project be considered bad practice? If yes, what would be the most viable way to perform generic operations with a database context non-generic?

  • Show generic Dbcontext and what it is not. This information may be the answer to your question. Having two Dbcontext is not bad practice, but the repetition of code is, so showing your code can lead us a better response!

  • What do you mean perform generic operations?

2 answers

4


Have only one Dbcontext may be a bad practice if the entities it contains have no relationship between them.

Following the approach DDD - Domain-driven design, when we are dealing with many entities, they should be grouped according to the context in which they relate.

For example, if your application has to deal with the area of stocks and personnel of a company, two Dbcontext, one for entities of Stocks other to the entities of Personal.

Behold here what is DDD.

In relation to your specific question I do not see the need to have two Dbcontext.

Note: Having more than one Dbcontext for the same Connection string no problem at all.

  • Good answer, substantiated technically, and that’s what’s important. Really what you quoted is good practice in relation to many entities, separating makes a big difference in performance and organization. Congratulations ...

3

Yes.

A context not only controls the loaded objects, but their states and all changes in records made within it.

Loading these objects in separate contexts, changes made to the same record for both contexts can be lost, causing inconsistency of information.

Try to use only your DbContext<T> for all the Controllers. I didn’t exactly understand the motivation to have a generic context and a non-generic one, but there’s no need for it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.