Connect WebApi with SqlServer Using Dot net via Code First Approach

Pamal Jayawickrama
2 min readJun 13, 2020

To demonstrate this I will use Vs Code not the visual Studio.

First download essential nugget packages for this.

Make a new folder Data in webApi project. Then create Data-context class inside data folder.

This Data-context class responsible for all CRUD operations with the database.So It should inherit from Db-context.

The easiest way to pass an instance of Db-context option class is by creating a Constructor.After that we add a property. It is going to return db-set of vehicle. vehicle is a model class that I created. If we create that property name as vehicles then entity framework will create a table inside a database with the same name. Look at the code bellow,

Then make a controller and name it as vehicle-controller.

Then make a constructor and pass data-context as a parameter.because it responsible for connection with database.

To work with the database we must need to create connection string.go to the startup class. Then add connection string to the services as follows.

To create Database use EnsureCreated(). That function check whether that database created or not.If it exits no action will be taken. This method only use full if you don’t want to update database near future.

You can see the database in SQL server

--

--