Abdus Sattar Bhuiyan
Abdus Sattar Bhuiyan

Reputation: 3074

What is the purpose of empty constructor of DbContext Class in EF Code First Approach?

I have the simple context class definition:

namespace PowerSupply.Persistance.Facade
{
    class PowerSupplyDBContext : DbContext
    {
        public PowerSupplyDBContext() : base("PowerSupplyDatabase")
        {

        }
    }
} 

There is nothing inside the body of

public PowerSupplyDBContext() : base("PowerSupplyDatabase")
            {

what is the purpose of this empty constructor. How does this empty constructor works?

Upvotes: 2

Views: 1447

Answers (2)

broccoli_rob
broccoli_rob

Reputation: 550

It's best practice to include an empty constructor in any class that might be used by a third party / other project / anywhere that the compiler can't catch a change in the class.

If you omit the empty constructor, and that class is used by a third party or in another one of your projects/applications, then you can't later change that class to include a constructor with arguments. Otherwise, all the uses of this class that previously did not rely on passing constructor arguments will break, because they will have no empty-constructor to reference.

Upvotes: 1

kkica
kkica

Reputation: 4104

It calls the constructor of the base class. So it is not empty. It just doesnt add something new.

There are many reasons you could use that "empty" constructor.

You may not have any new properties, or you instantiate those properties somewhere else (i dont recommend)

You may just want to add functionality (new methods) so you extend the class, and implement new methods using the properties and methods of base class. So you dont need the constructor to do something new, opposed to the base class.

Or it has many constructors, and you use the empty constructor in circumstances you need to use limited functionality of the class, or default values.

Upvotes: 5

Related Questions