Database First In .Net Core 2.0 CRUD Operation - Part One

Angular 5

In my previous post, I explained how to create an Angular5 application in Visual Studio 2017 using .NET Core templates which you can find here.

In this series of posts, I will explain the Create, Read, Update, Delete (CRUD) using Angular5 with .NET Core 2 API.

In this post, we will see how to do Database First set up in Angular(.NET Core 2.0 project) and will set up the Employee API.

Prerequisite

  • Visual Studio 2017 Community edition, download here
  • .NET Core 2.0 SDK from here (I have written a post to install SDK here)

Create the Angular application using .NET Core 2.0 template in VS 2017

Once you have all these installed, open your Visual Studio 2017 -> Create New Project -> Select Core Web application.

Angular 5

Click on OK and in the next window, select Angular, as shown below.

Angular 5

Visual Studio will create a well-structured application for you (Note that I have manually added Models folder as we will require this in the future).

Angular 5

I will not go deep into the Angular structure in this post but if you require more details then I have written a detailed post on Angular and .NET Core 2.0 which you find here.

Once you run the application on IISExpress, it will have the landing page as below.

Angular 5

Creation of Employee Database

Let us create Employee database in SQL, you can use below queries to create the database and table.

  1. CREATE DATABASE AngularCRUDTest;  
  2. CREATE TABLE Employees(StudentId[bigint] IDENTITY(1, 1) NOT NULL, EmpName varchar(50), EmpAge int, EmpCity varchar(50), EmpCountry varchar(50), CONSTRAINT[PK_Student] PRIMARY KEY CLUSTERED([StudentId] ASC));  
  3. INSERT INTO Employees(EmpName, EmpAge, EmpCity, EmpCountry) VALUES('Neel', 27, 'Pune''India');  
  4. INSERT INTO Employees(EmpName, EmpAge, EmpCity, EmpCountry) VALUES('Neel2', 27, 'Pune''India');  
  5. INSERT INTO Employees(EmpName, EmpAge, EmpCity, EmpCountry) VALUES('Neel3', 27, 'Pune''India');  

Once the database is created successfully, it will look as below.

Angular 5
Add EntityFramework references

Once the database is created, let us add EntityFrameworkCore.SqlServer(Microsoft SQL Server database provider for Entity Framework Core), this will help us to go further with EntityFramework operations.

Search with "Microsoft.EntityFrameworkCore.SqlServer" in Nuget Package Manager and click on Install,

Angular 5

As we are going to use Database First development approach, we need to install the additional packages below as well:

  • Microsoft.EntityFrameworkCore.Tools(Includes Scaffold-DbContext, Add-Migration, and Update-Database)

    Angular 5
  • Microsoft.EntityFrameworkCore.SqlServer.Design(Design-time Entity Framework Core Functionality for Microsoft SQL Server)

    Angular 5

Entity Model creation

Once we have installed all required references, let us add required context and model classes from existing databases.

.Net Team has made this step easier and now we just need to run below line in Package Manager Console,

  1. Scaffold-DbContext "Server=.\SQL2012;Database=AngularCRUDTest;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models  

Here use the connection string as per your database and the –OutputDir attribute allows you to specify the location of the files generated. In this case, we’ve set it to Models(folder which we have added previously).

Angular 5

Once you run the above code, it will create the Context class and Employee class into the Models folder as shown below,

Angular 5

AngularCRUDTestContext.cs class here,

  1. using Microsoft.EntityFrameworkCore;  
  2. namespace NeelAngular4CRUD.Models {  
  3.         public partial class AngularCRUDTestContext: DbContext {  
  4.                 public virtual DbSet Employees {  
  5.                     get;  
  6.                     set;  
  7.                 }  
  8.                 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  9.                 {  
  10.                         if (!optionsBuilder.IsConfigured)  
  11.                         {  
  12.                           #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.optionsBuilder.UseSqlServer(@ "Server=.\SQL2012;Database=AngularCRUDTest;Trusted_Connection=True;");  
  13.  }  
  14.  }  
  15.  protected override void OnModelCreating(ModelBuilder modelBuilder) {  
  16.      modelBuilder.Entity(entity => {  
  17.          entity.HasKey(e => e.StudentId);  
  18.          entity.Property(e => e.EmpCity).HasMaxLength(50).IsUnicode(false);  
  19.          entity.Property(e => e.EmpCountry).HasMaxLength(50).IsUnicode(false);  
  20.          entity.Property(e => e.EmpName).HasMaxLength(50).IsUnicode(false);  
  21.      });  
  22.  }  
  23.  }  
  24.  }  

Employees.cs class represents the Employees table here,

  1. namespace NeelAngular4CRUD.Models {  
  2.     public partial class Employees {  
  3.         public long StudentId {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public string EmpName {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public int ? EmpAge {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string EmpCity {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string EmpCountry {  
  20.             get;  
  21.             set;  
  22.         }  
  23.     }  
  24. }  

Once this is done, we will add the connection string into appsettings.json file, in .Net core we have json file instead of web.config files here,

  1. {  
  2.     "ConnectionStrings": {  
  3.         "i."null,  
  4.         "AngularCRUDTestDatabase""Server=.\\SQL2012;Database=AngularCRUDTest;Trusted_Connection=True;"  
  5.     },  
  6.     "Logging": {  
  7.         "LogLevel": {  
  8.             "Default""Warning"  
  9.         }  
  10.     }  
  11. }  

Next step is to add DB Context to the Startup.cs class.

Add below references into the Startup.cs class,

using NeelAngular5CRUD.Models; using Microsoft.EntityFrameworkCore;

Add below lines into the ConfigureService method,

services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("AngularCRUDTestDatabase")));

Statup.cs class looks like below here,

  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.AspNetCore.SpaServices.Webpack;  
  4. using Microsoft.Extensions.Configuration;  
  5. using Microsoft.Extensions.DependencyInjection;  
  6. using NeelAngular4CRUD.Models;  
  7. using Microsoft.EntityFrameworkCore;  
  8. namespace NeelAngular4CRUD {  
  9.     public class Startup {  
  10.         public Startup(IConfiguration configuration) {  
  11.             Configuration = configuration;  
  12.         }  
  13.         public IConfiguration Configuration {  
  14.             get;  
  15.         } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) {  
  16.         services.AddMvc(); // Add ASPNETCoreDemoDBContext services. services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("AngularCRUDTestDatabase")));  
  17. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
  18. public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
  19.     if (env.IsDevelopment()) {  
  20.         app.UseDeveloperExceptionPage();  
  21.         app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {  
  22.             HotModuleReplacement = true  
  23.         });  
  24.     } else {  
  25.         app.UseExceptionHandler("/Home/Error");  
  26.     }  
  27.     app.UseStaticFiles();  
  28.     app.UseMvc(routes => {  
  29.         routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");  
  30.         routes.MapSpaFallbackRoute(name: "spa-fallback", defaults: new {  
  31.             controller = "Home", action = "Index"  
  32.         });  
  33.     });  
  34. }  
  35. }  
  36. }  

As shown in the above code, we are passing configuration to AddDbContext so we are required to add a constructor in AngularCRUDTestContext that accepts DbContextOptions.

For that, go to AngularCRUDTestContext class and remove OnConfiguring method as we do not need it and add the constructor to allow the configuration to be passed into the context by dependency injection.

public AngularCRUDTestContext(DbContextOptions options) : base(options)  { }

If we do not add the above constructor, then after running, we will get the below exception.

Angular 5

That is it. We have completed all the required code.

Add API Controller with actions using Entity Framework

Right-click on Controllers folder -> Add new Controller -> select API controller with actions using Entity Framework.

Angular 5

In next window, select Employees in Model drop-down and AngularCRUDTestContext in Data context drop-down.

Angular 5

Once you click on Add, an EmployeeController API class will be created with all the CRUD operations,

Let us test our API. Run the application.

http://localhost:53008/api/Employees

Angular 5
As you can see, all the employees which we added to the database are returned which shows our code is working fine.

In my next post, we will add different Angular component class to do the CRUD operation using the API we created in this post and will show the details on UI.


Similar Articles