What is the purpose of the OnModelCreating method and how does it work?

3

I'm studying Fluent API and I'm having this doubt, I saw that this method can be empty with no implementation. So how useful is it and how does the OnModelCreating method work in the context class that belongs to the DbContex class?

    
asked by anonymous 14.09.2015 / 17:43

1 answer

2

According to the MSDN documentation about :

  

This method is called when the derived context has been initialized, but the model has been locked down and used to initialize the context. The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down.

Translating:

  

This method is called when the template for a derived context was initialized, but before the template was blocked and used to initialize the context. The default implementation of this method does nothing, but can be overridden in a derived class such that the model can still be configured before being blocked.

It serves to define extra associations between models, primary keys, foreign keys, perform some checks on context, etc.

Associations are set through the Fluent API .

Optively speaking, working with OnModelCreating is less interesting than defining the associations within each Model by attributes. This is because, as the system grows, the complexity of setting up the base by this context method increases, and maintenance becomes more difficult.

We have several answers regarding the Fluent API here on the site . I think it's worth a look.

    
14.09.2015 / 17:50