Using Entity Framework Core with Asp.net Core, VS 2017

If you are starting a new application, you can start right from the code/model first approach. In most cases you have an existing database with an existing application, you will need to use scaffolding to create models automatically.

Code/Model First Approach

You need to install few packages from nuget package console/manager. I am trying to build a habit of using console now otherwise being a lazy developer i jumped on the UI train first, to avoid remembering the names of packages.

You need to open the nuget package console and install the following packages

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools

Installing the above packages and their dependencies will help in communicating with the database and database management. Tools will help you to manage the database migrations.

Once they are installed, you need to make sure that our application is aware of a database using a connection string. Connections string can be passed in the database contexts but its better to manage connection string outside of the code. Ideally in a config/settings file. Lets create a settings file which holds the connection string for you.

  • Open the Startup.cs file.
  • Add a new static property “Configuration” of type “IConfigurationRoot” with blank getter and setter.

    public IConfigurationRoot Configuration { get; set; }

  • If you dont have a constructor for Startup class, create a constructor with the following signatures.

    public Startup(IHostingEnvironment env) { }

  • Create a new configuration builder object. Set a basepath and add a json file for reading configurations from.
    public Startup(IHostingEnvironment env) {
        Configuration = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables()
        .Build();
    }
    
  • Now open the “Add File” dialog for the project and add appsettings.json file to the project.
    appsettings
  • Appsettings.json file contains the connection string with a default value. Edit your connection string to provide the database server details and database name. (I am avoiding username and password for the sake of simplicity).
    {
      "ConnectionStrings": {
        "MyConnection": "Server=.\\SQLExpress;Database=VenuesDb;Trusted_Connection=True;MultipleActiveResultSets=true"
      }
    }
    
  • By default the connection string name is “DefaultConnection” I changed the name to “MyConnection” to demonstrate you can keep any name for connection string.
  • “.\\SQLExpress” is my SQL Server instance name. “VenuesDb” is my database name. Database does not exist right now, it will be created with the name “VenuesDb”.

Now that you have identified the name of the database and also provided the necessary information to create the database i.e., a current logged in user, an SQL Server instance and a database name. We are ready to create a database context which will be used to communicate with the database in our application. Create a new file in Models folder with the name “<DatabaseName>Context.cs” in our case its “VenuesDbContext.cs

Database context should be inherited from DbContext. The file has a constructor which will help you to inject connection string and other DbContextOptions. 

Create another model with the name “Venue.cs” which will define a table structure for the database.

Now you need to inform the DbContext about this new model, so that when creating the database a table for venues should also be created. Lets get back to the VenuesDbContext.cs file with few changes.

Venue class is added as a DbSet property in the context class. You can also see a new override OnModelCreating to make any changes to the tables before they actually build in the database. As an example you can change the name from plural to singular.

You are almost done. One last thing is to register your DbContext with the dependency injection service provider. We added a constructor to the Startup class in the beginning. Updated start of Startup.cs file is as follows

From line number 33 – 36 we have registered our DbContext with the services for dependency injection.

We can now either use migration to create the database or use

context.Database.EnsureCreated();

For simplicity, let’s use EnsureCreated().

  • Add a new parameter of DbContext to configure method in Startup class.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, VenuesDbContext context)

  • At the end of the Configure method call the following method from the context object.

    context.Database.EnsureCreated();

  • EnsureCreated() ensures the creation of the database at this point of execution.

Updating the Database

To update a database it is recommended to use migration in asp.net core with entity framework core.

Database First Approach

For database first most of the steps are same with few exceptions. You will not need to create DbContext and Model classes. You will not need to call context.Database.EnsureCreated(). All you need to do is to install the two packages from nuget package.

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools

After installation keep the nuget package console open and write the following command

Scaffold-DbContext “Server=.\SQLExpress;Database=VenuesDb;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Scaffold-DbContext command creates the context as well as all the necessary Model classes to interact with the database.

  • Open the context class and remove OnConfiguring override method which has the connection string information.
  • Startup class should have the constructor just like code/model first approach with the appsetting.json file for connection string configurations.
  • Create the constructor with the same arguments as we have done with the code/model first approach above.
  • Add the dependency injection by registering context with dependency injection. This is again same as above in code/model first approach.

Updating the Database

Whether you are using code first or database first, to update a database it is recommended to use migration in asp.net core with entity framework core. Having said that, you can remove all the models and recreate the models every time you make a change in the database. In that case it’s better to keep you models in a separate table like “Data” or “EFModels” so that you know this folders needs to be blank and it doesn’t interfere with your other models.

Migration

Migrations help the developers to maintain the databases from within the code. If you have created a DbContext class, migration will find out this class and create all necessary database upgrade or downgrade scripts. If you are creating the context file for the first time you will need to use

PM> Add-Migration <migration name>

You will need to enter this using nuget package console. Migration name can be anything that you want to use as a reference. Migration name becomes the name of the file along with a random number.

Add-Migration

It will create a new folder in the project with the name “Migrations” and automatically create a new file with the name of migration and a random number.

Migration Folder

It also contains a snapshot file. Snapshot file contains the mirror information of current database version. Whenever system migrates it will check the current state of the database using this snapshot file to speed up the process of migration. Now run Following command in nuget package console

PM> Update-Database

This is physical create database into the database server.

For further details
https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db
https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s