Is base.OnModelCreating(modelBuilder) necessary?

entity-framework entity-framework-6

Question

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?

1
12
9/19/2016 2:53:35 PM

Accepted Answer

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.

9
8/20/2019 4:54:47 PM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow