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

Asked

Viewed 294 times

3

I am studying Fluent API and I am with this doubt, I saw that this method can be empty, without any implementation. So what is its usefulness and how the Onmodelcreating method works that is in the context class that belongs to the Dbcontex class?

1 answer

2


According to MSDN documentation on:

This method is called when the model for a derived context has been initialized, but before 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 model for a derived context was initialized, but before the model was blocked and used to initialize the context. The standard implementation of this method does nothing, but can be replaced in a derived class such that the model can still be configured before it is locked.

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

The associations are defined through the Fluent API.

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

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

  • So from what I understand in its explanations, the Fluent API can only be defined in this method other than the correct Data Annotations?

  • @Kellysoares That’s right.

Browser other questions tagged

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