Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is base.OnModelCreating(modelBuilder) necessary?

I'm overriding OnModelCreating, and in the method there's the line base.OnModelCreating(modelBuilder);

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
}

Looking at code samples and manuals on how to implement this, I get confused as to wether I need it or not. Sometimes it's there, sometimes not. Sometimes at the beginning of the method, other times at the end.

What should I do with it?

like image 263
Garth Marenghi Avatar asked Sep 19 '16 14:09

Garth Marenghi


2 Answers

Here what says Pawel Kadluczka - MSFT ...

At the moment it does not really matter. Both OnModelCreating and Seed methods don't have any implementation (i.e. the bodies of the functions are empty) in their base classes. Therefore calling into the base class is basically a no-op. I don't think there are any plans to change it (especially for Seed method - how we would know what data to put in the database?)

In general protected methods can have some implementation in base classes. In that case this is up to the developer who derives from such a class to decide whether s/he would like to take advantage of the functionality provided in the method in the base class or not. If the developer thinks that s/he only would like to add something to the functionality provided by the method in the base class s/he would call into this method. Otherwise s/he would not call into the method of the base class and would provide all the required functionality in the method on the derived class.

Reference : Link

like image 22
Sampath Avatar answered Sep 28 '22 13:09

Sampath


According to the documentation, it doesn't matter if you inherit directly from the DbContext class:

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.

In other words, since is does nothing by definition, calling base.OnModelCreating is not necessary, but at the same time will not hurt if called - that's why Sometimes it's there, sometimes not. Sometimes at the beginning of the method, other times at the end.

like image 125
Ivan Stoev Avatar answered Sep 28 '22 13:09

Ivan Stoev