In Focus

Generate Entity Framework Core Code First Models From Database In ASP.NET Core

In this article, I have explained how to generate Entity Framework Core code-first models from the database in ASP.NET Core.

Implementation

While starting a new project, sometimes a database may exist and if we can generate code-first models from the existing database, then it will reduce our effort. Now, let's see how to generate Entity Framework Core Code-First models from the database in ASP.NET Core.

First, open Visual Studio (I am using VS2017 Community edition) and create a new ASP.NET Core project.

Generate Entity Framework Core Code First Models From Database In ASP.NET Core

And then, for demo purposes, I have created a sample table called "Employee" in my database. Below is the script.

  1. USE [Demo]  
  2. GO  
  3.   
  4. CREATE TABLE [dbo].[EMPLOYEE](  
  5.         [Id] [intNOT NULL IDENTITY PRIMARY KEY,  
  6.         [Name] [varchar](100) NOT NULL,  
  7.         [Designation] [varchar](100) NOT NULL,  
  8.         [SALARY] [intNULL,  
  9.         [Branch] [varchar](100) NULL  
  10. )  
  11. GO  

Now go to Tools-> NuGet Package Manager -> Package Manager Console like shown in the below screenshot.

Generate Entity Framework Core Code First Models From Database In ASP.NET Core 

Now, to generate the EF Core code-first models from the database in ASP.NET Core, the Scaffold-DbContext command is used. Below is the syntax to run Scaffold-DbContext command.

PM > Scaffold-DbContext ConnectionString Provider -OutputDir DirectoryName

Below is the sample command I have used to generate the models from the database.

PM> Scaffold-DbContext "Server=xxx;Database=Demo;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

It will generate the model classes and DbContext file. Below is the generated Employee.cs & DemoContext.cs file contents.

Employee.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace AspNetCore2Application.Models  
  5. {  
  6.     public partial class Employee  
  7.     {  
  8.         public int Id { getset; }  
  9.         public string Name { getset; }  
  10.         public string Designation { getset; }  
  11.         public int? Salary { getset; }  
  12.         public string Branch { getset; }  
  13.     }  
  14. }  

DemoContext.cs

  1. using System;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using Microsoft.EntityFrameworkCore.Metadata;  
  4.   
  5. namespace AspNetCore2Application.Models  
  6. {  
  7.     public partial class DemoContext : DbContext  
  8.     {  
  9.         public DemoContext()  
  10.         {  
  11.         }  
  12.   
  13.         public DemoContext(DbContextOptions<DemoContext> options)  
  14.             : base(options)  
  15.         {  
  16.         }  
  17.   
  18.         public virtual DbSet<Employee> Employee { getset; }  
  19.   
  20.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  21.         {  
  22.             if (!optionsBuilder.IsConfigured)  
  23.             {  
  24. #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.  
  25.                 optionsBuilder.UseSqlServer("Server=xxx;Database=Demo;Trusted_Connection=True;");  
  26.             }  
  27.         }  
  28.   
  29.         protected override void OnModelCreating(ModelBuilder modelBuilder)  
  30.         {  
  31.             modelBuilder.Entity<Employee>(entity =>  
  32.             {  
  33.                 entity.ToTable("EMPLOYEE");  
  34.   
  35.                 entity.Property(e => e.Id).ValueGeneratedNever();  
  36.   
  37.                 entity.Property(e => e.Branch)  
  38.                     .HasMaxLength(100)  
  39.                     .IsUnicode(false);  
  40.   
  41.                 entity.Property(e => e.Designation)  
  42.                     .IsRequired()  
  43.                     .HasMaxLength(100)  
  44.                     .IsUnicode(false);  
  45.   
  46.                 entity.Property(e => e.Name)  
  47.                     .IsRequired()  
  48.                     .HasMaxLength(100)  
  49.                     .IsUnicode(false);  
  50.   
  51.                 entity.Property(e => e.Salary).HasColumnName("SALARY");  
  52.             });  
  53.         }  
  54.     }  
  55. }  

Using Database Names

 
Now, if you look into the Employee.cs, the table name and column name are not matching. My table name is EMPLOYEE but the class name is Employee. This is because, by default, the database names are changed to C# name style conventions. If you want to keep the database names, then you have to pass an additional parameter -UseDatabaseNames in your command. Now, the modified command looks like the following.

Scaffold-DbContext "Server=xxx;Database=Library;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -UseDatabaseNames

Now, if I run the above command, it throws the below error.

The following file(s) already exist in directory C:\Users\xxxx\Documents\Visual Studio 2017\Projects\Asp.NetCore2.0Application\Asp.NetCore2.0Application\Models: DemoContext.cs,Employee.cs. Use the Force flag to overwrite these files.

So, we need to override the existing files. For that, we need to pass -Force parameter into the command. Now, our modified command will be like the following.

Scaffold-DbContext "Server=xxx;Database=Library;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -UseDatabaseNames -Force

If you run this command, you will get the below class with the names, the same as the database table.

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace AspNetCore2Application.Models  
  5. {  
  6.     public partial class EMPLOYEE  
  7.     {  
  8.         public int Id { getset; }  
  9.         public string Name { getset; }  
  10.         public string Designation { getset; }  
  11.         public int? SALARY { getset; }  
  12.         public string Branch { getset; }  
  13.     }  
  14. }  

Using Data Annotations

 
After that, let's look into DemoContext.cs. All the models are configured using FluentAPI. This is the default option. But if you want to use DataAnnotation attributes to configure the models, then we need to pass -DataAnnotations parameter in the command like below.

PM> Scaffold-DbContext "Server=xxx;Database=Demo;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -UseDatabaseNames -force -DataAnnotations

Now, you can see the modified Employee.cs and DemoContext.cs file contents.

Employee.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5.   
  6. namespace AspNetCore2Application.Models  
  7. {  
  8.     public partial class EMPLOYEE  
  9.     {  
  10.         public int Id { getset; }  
  11.         [Required]  
  12.         [StringLength(100)]  
  13.         public string Name { getset; }  
  14.         [Required]  
  15.         [StringLength(100)]  
  16.         public string Designation { getset; }  
  17.         public int? SALARY { getset; }  
  18.         [StringLength(100)]  
  19.         public string Branch { getset; }  
  20.     }  
  21. }  

DemoContext.cs

  1. using System;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using Microsoft.EntityFrameworkCore.Metadata;  
  4.   
  5. namespace AspNetCore2Application.Models  
  6. {  
  7.     public partial class DemoContext : DbContext  
  8.     {  
  9.         public DemoContext()  
  10.         {  
  11.         }  
  12.   
  13.         public DemoContext(DbContextOptions<DemoContext> options)  
  14.             : base(options)  
  15.         {  
  16.         }  
  17.   
  18.         public virtual DbSet<EMPLOYEE> EMPLOYEE { getset; }  
  19.   
  20.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  21.         {  
  22.             if (!optionsBuilder.IsConfigured)  
  23.             {  
  24. #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.  
  25.                 optionsBuilder.UseSqlServer("Server=xxx;Database=Demo;Trusted_Connection=True;");  
  26.             }  
  27.         }  
  28.   
  29.         protected override void OnModelCreating(ModelBuilder modelBuilder)  
  30.         {  
  31.             modelBuilder.Entity<EMPLOYEE>(entity =>  
  32.             {  
  33.                 entity.Property(e => e.Id).ValueGeneratedNever();  
  34.   
  35.                 entity.Property(e => e.Branch).IsUnicode(false);  
  36.   
  37.                 entity.Property(e => e.Designation).IsUnicode(false);  
  38.   
  39.                 entity.Property(e => e.Name).IsUnicode(false);  
  40.             });  
  41.         }  
  42.     }  
  43. }  

Conclusion

 
I hope you learned how to generate EF Core code-first models from the database in ASP.NET Core. Do you like this tutorial? Help me improve by posting your comments and feedback below.