Click here to Skip to main content
14,027,303 members
Click here to Skip to main content
Add your own
alternative version


29 bookmarked
Posted 17 May 2018
Licenced CPOL

ASP.NET Core Blazor CRUD using Entity Framework and Web API

, 17 May 2018
Rate this:
Please Sign up or sign in to vote.
In this article, we will see how to create a simple CRUD application for ASP.NET Core Blazor using Entity Framework and Web API.


* Kindly view my Youtube Video Link to learn ASP.NET Core Blazor CRUD using Entity Framework and Web API.

In this article, we will see how to create a simple CRUD application for ASP.NET Core Blazor using Entity Framework and Web API. Blazor is a new framework introduced by Microsoft. I love to work with Blazor as this makes our SPA full stack application development in a simpler way and yes, now we can use only one language as C#. Before Blazor, we had been using ASP.NET Core with the combination of Angular or ReactJs, now with the help of Blazor support, we can create our own SPA application directly with C# Code.If you start your SPA application development using Blazor, surely you will love it and it was that much simpler and fun to work with Blazor. The only drawback now we have is as the Blazor is newly introduced framework and it’s still in the experimental phase, once we get the complete version, it will be more fun to work with application developments.

In this article, we will see how to create CRUD web Application using ASP.NET Core Blazor.

  • C: (Create): Insert new Student Details into the database using ASP.NET Core, Blazor, EF and Web API.
  • R: (Read): Select Student Details from the database using ASP.NET Core, Blazor, EF and Web API.
  • U: (Update): Update Student Details to the database using ASP.NET Core, Blazor, EF and Web API
  • D: (Delete): Delete Student Details from the database using ASP.NET Core, Blazor, EF and Web API.

We will be using Web API and EF to perform our CRUD operations. Web API has the following four methods as Get/Post/Put and Delete, where:

  • Get is to request for the data (Select)
  • Post is to create a data (Insert)
  • Put is to update the data (Update)
  • Delete is to delete data (Delete)



Make sure that you have installed all the prerequisites in your computer. If not, then download and install all, one by one. Note that since Blazor is the new framework, we must have installed preview of Visual Studio 2017 (15.7) or above.

Using the Code

Step 1 - Create a Database and a Table

We will be using our SQL Server database for our WEB API and EF. First, we create a database named StudentsDB and a table as StudentMaster. Here is the SQL script to create a database table and sample record insert query in our table. Run the query given below in your local SQL Server to create a database and a table to be used in our project.


-- 1) Check for the Database Exists .If the database is exist then drop and create new DB
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'StudentsDB' )


USE StudentsDB

-- 1) //////////// StudentMasters

IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'StudentMasters' )
DROP TABLE StudentMasters

CREATE TABLE [dbo].[StudentMasters](
        [StdName] [varchar](100) NOT NULL,
        [Email]  [varchar](100) NOT NULL,
        [Phone]  [varchar](20) NOT NULL,
        [Address]  [varchar](200) NOT NULL

-- insert sample data to Student Master table
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])
     VALUES ('Shanu','','01030550007','Madurai,India')

INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])
     VALUES ('Afraz','','01030550006','Madurai,India')

INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])
     VALUES ('Afreen','','01030550005','Madurai,India')

     select * from [StudentMasters] 

Step 2 - Create ASP.NET Core Blazor Application

After installing all the prerequisites listed above and ASP.NET Core Blazor Language Services, click Start >> Programs >> Visual Studio 2017 >> Visual Studio 2017 on your desktop. Click New >> Project. Select Web >> ASP.NET Core Angular Web Application. Enter your project name and click OK.

Select Blazor (ASP.NET Core hosted) and click ok.

After creating ASP.NET Core Blazor Application, wait for few seconds. You will see the below structure in solution explorer.

What is New in ASP.NET Core Blazor Solution?

When we create our new ASP.NET Core Blazor application, we can see as there will be 3 projects will be automatically created in the Solution Explorer.

Client Project

The first project created as the Client project and it will be as our Solutionname.Client and here we can see our Solutionname as “BlazorASPCORE”. As the project is named as client, this project will be mainly focused for all the client-side view. Here, we will be adding all our page view to be displayed in the client side in browser.

We can see as few of sample page has been already added here and we can also see a shared folder which is the same like our MVC application where will be having the Sharedfolder and Layout page for the Master page. Here, in Blazor, we have the MainLayout which will work like the Master page and NavMenu for the left side menu display.

Server Project

As the name indicates, this project will be used as a Server project. This project is mainly used to create all our Controllers and WEB API Controllers to perform all business logic and perform CRUD operation using WEB APIs. In our demo application, we will be adding a Web API in this Server project and all the WEB API in our Client application. This Server project will work like get/set the data from database and from our Client project, we bind or send the result to this server to perform the CRUD operation in database.

Shared Project

As the name indicates, this project works like a shared project. This project works as a Model for our Server project and for the Client project. The Model declared in this Shared project will be used in both the Server and in the Client project. We also install all the packages needed for our project here, for example to use the Entity Framework, we install all the packages in this Shared project.

Run to Test the Application

When we run the application, we can see that the left side has navigation and the right side contains the data. We can see as the default sample pages and menus will be displayed in our Blazor web site. We can use the pages or remove it and start with our own page.

Now let’s see how to add new page perform the CRUD operation for maintaining student details.

Using Entity Framework

To use the Entity Framework in our Blazor application, we need to install the below packages:

Install the Packages

Go to Tools and then select -> NuGet Package Manager -> Package Manager Console.

You can see the Console at the bottom of the VS 2017 IDE and at the right side of the combobox on the console, select the Default project as your shared project ”Select Shared”.

  1. You can see the PM> and copy and paste the below line to install the Database Provider package. This package is used to set the database provider as SQL Server.
    <font color="#000000" face="Calibri" size="3">
    Install-Package Microsoft.EntityFrameworkCore.SqlServer</font>

    We can see as the package is installed in our Shared folder.

    Install the Entity Framework.

  2. You can see the PM> and copy and paste the below line to install the EF package.
    Install-Package Microsoft.EntityFrameworkCore.Tools

  3. You can see the PM> and copy and paste the below line set the Connection string and create DB Context. This is an important part as we give our SQL Server name, Database Name and SQL server UID and SQL Server Password to connect to our database for performing the CRUD operation. We also give our SQL Table name to create the Model class in our Shared project.
    Scaffold-DbContext "Server= YourSqlServerName;Database=StudentsDB;
    user id= YourSqlUID;password= YourSqlPassword;Trusted_Connection=True;
    MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer
    -OutputDir Models -Tables StudentMasters

    Press enter create connection string, Model Class and Database Context.

    We can see StudentMasters Model class and StudentsDBContext class has been created in our Shared project. We will be using this Model and DBContext in our Server project to create our Web API to perform the CRUD operations.

Creating Web API for CRUD Operation

To create our WEB API Controller, right click Controllers folder. Click Add New Controller.

Here, we will be using Scaffold method to create our WEB API. We select API Controller with actions, using Entity Framework.

Select our Model and DatabaseContext from the Shared project.

Select our StudentMasters Model from the Shared Project for performing the CRUD operation.

Select the Data Context Class as our StudentsDBContext from the Shared project. Our Controller name will be automatically added. If you need, you can change it and click the ADD.

Our WEB API with Get/Post/Put and Delete method for performing the CRUD operation will be automatically created and we do not need to write any code in Web API now as we have used the Scaffold method for all the actions and methods add with code.

To test Get method, we can run our project and copy the GET method API path. Here, we can see our API path to get api/StudentMasters/.

Run the program and paste API path to test our output.

Now, we will bind all this WEB API Json result in our View page from our Client project.

Working with Client Project

First, we need to add the new Razor view page.

Add Razor View

To add the Razor view page, right click the Pages folder from the Client project. Click on Add >> New Item.

Select Razor View >> Enter your page name. Here, we have given the name as Students.chtml.

In Razor view Page, we have 3 parts of code as first is the Import part where we import all the references and models for using in the view, HTML design and data bind part and finally, we have the function part to call all the web API to bind in our HTML page and also to perform client-side business logic to be displayed in View page.

Import Part

First, we import all the needed support files and references in our Razor View page. Here, we have first imported our Model class to be used in our view and also imported HTTPClient for calling the Web API to perform the CRUD operations.

@using BLAZORASPCORE.Shared.Models
@page "/Students"
@using Microsoft.AspNetCore.Blazor.Browser.Interop
@inject HttpClient Http

HTML Design and Data Bind Part

Next, we design our Student details page to display the student details from the database and create a form to Insert and update the Student details. We also have Delete button to delete the student records from the database.

For binding in Blazor, we use the bind="@stds.StdId" and to call the method using onclick="@AddNewStudent".

<h1> ASP.NET Core BLAZOR CRUD demo for Studetns</h1>
<hr />
<table width="100%" style="background:#05163D;color:honeydew">
        <td width="20">&nbsp;</td>
            <h2> Add New Student Details</h2>
        <td align="right">
            <button class="btn btn-info" onclick="@AddNewStudent">Add New Student</button>
        <td width="10">&nbsp;</td>
        <td colspan="2"></td>
<hr />
    <table class="form-group">
                <label for="Name" class="control-label">Student ID</label>
                <input type="text" class="form-control" bind="@stds.StdId" readonly />
            <td width="20">&nbsp;</td>
                <label for="Name" class="control-label">Student Name</label>
                <input type="text" class="form-control" bind="@stds.StdName" />
                <label for="Email" class="control-label">Email</label>
                <input type="text" class="form-control" bind="@stds.Email" />
            <td width="20">&nbsp;</td>
                <label for="Name" class="control-label">Phone</label>
                <input type="text" class="form-control" bind="@stds.Phone" />
                <label for="Name" class="control-label">Address</label>
                <input type="text" class="form-control" bind="@stds.Address" />
            <td width="20">&nbsp;</td>
                <button type="submit" class="btn btn-success"

                 onclick="@(async () => await AddStudent())" style="width:220px;">Save</button>

<table width="100%" style="background:#0A2464;color:honeydew">
        <td width="20">&nbsp;</td>
            <h2>Student Details</h2>

        <td colspan="2"></td>

@if (student == null)
    <table class="table">
                <th>Student ID</th>
                <th>Student Name</th>

            @foreach (var std in student)

                    <td><button class="btn btn-primary"

                     onclick="@(async () => await EditStudent(@std.StdId))"

                    <td><button class="btn btn-danger"

                     onclick="@(async () => await DeleteStudent(@std.StdId))">Delete</button></td>

Function Part

function part to call all the web API to bind in our HTML page and also to perform client-side business logic to be displayed in View page. In this Function, we create a separate function for Add, Edit and Delete the student details and call the Web API Get, Post, Put and Delete method to perform the CRUD operations and in HTML, we call all the function and bind the results.

@functions {
    StudentMasters[] student;

    StudentMasters stds = new StudentMasters();
    string ids = "0";
    bool showAddrow = false;
    protected override async Task OnInitAsync()
        student = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");

    void AddNewStudent()
        stds = new StudentMasters();
    // Add New Student Details Method
    protected async Task AddStudent()
        if (stds.StdId == 0)

            await Http.SendJsonAsync(HttpMethod.Post, "/api/StudentMasters/", stds);

            await Http.SendJsonAsync(HttpMethod.Put, "/api/StudentMasters/" + stds.StdId, stds);
        stds = new StudentMasters();
        student = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");
    // Edit Method
    protected async Task EditStudent(int studentID)
        ids = studentID.ToString();
        stds = await Http.GetJsonAsync<StudentMasters>
               ("/api/StudentMasters/" + Convert.ToInt32(studentID));
    // Delte Method
    protected async Task DeleteStudent(int studentID)
        ids = studentID.ToString();
        await Http.DeleteAsync("/api/StudentMasters/" + Convert.ToInt32(studentID));

        // await Http.DeleteAsync("/api/StudentMasters/Delete/" + Convert.ToInt32(studentID));

        student = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");

Navigation Menu

Now we need to add this newly added Students Razor page to our left Navigation. For adding this, open the Shared Folder and open the NavMenu.cshtml page and add the menu.

<li class="nav-item px-3">
            <NavLink class="nav-link" href="/Students">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Students Details

Build and Run the Application

Points of Interest

Note as when creating the DBContext and setting the connection string, don’t forget to add your SQL connection string. Hope you all like this article and in the next article, we will see more examples to work with Blazors and it's really very cool and awesome to work with Blazor.


  • 2018-05-18:


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

You may also be interested in...


Comments and Discussions

Questionerrors on my blazor app when i apply this url: http://localhost:53960/api/StudentMasters/ Pin
Member 1279843528-Jan-19 5:20
memberMember 1279843528-Jan-19 5:20 
AnswerRe: errors Build blazor app i apply this url: http://localhost:53960/api/StudentMasters/ Pin
Member 1279843528-Jan-19 5:23
memberMember 1279843528-Jan-19 5:23 
QuestionError on build Pin
Mike Horn MSU2-Nov-18 6:20
memberMike Horn MSU2-Nov-18 6:20 
I'm having an issue after running the Scaffold-DbContext command

Error in 32 - When running Scaffold
Severity Code Description Project File Line Suppression State
Error MSB3073 The command "dotnet "C:\Users\hornm\.nuget\packages\\0.6.0\targets\../tools/illink/illink.dll"
-l none --verbose --strip-security true --exclude-feature com --exclude-feature sre
-v false -c link -u link -b true -d "C:\Users\hornm\.nuget\packages\\0.6.0\targets\../tools/mono/bcl/"
-d "C:\Users\hornm\.nuget\packages\\0.6.0\targets\../tools/mono/bcl/Facades/"
-o "C:\Users\hornm\source\repos\WebApplication32\WebApplication32.Client\obj\Debug\netstandard2.0\blazor\linker/"
-x "C:\Users\hornm\.nuget\packages\\0.6.0\targets\BuiltInBclLinkerDescriptor.xml"
-x "C:\Users\hornm\source\repos\WebApplication32\WebApplication32.Client\obj\Debug\netstandard2.0\blazor\linker.descriptor.xml"
-a "C:\Users\hornm\.nuget\packages\microsoft.aspnetcore.blazor\0.6.0\lib\netstandard2.0\Microsoft.AspNetCore.Blazor.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.aspnetcore.blazor.browser\0.6.0\lib\netstandard2.0\Microsoft.AspNetCore.Blazor.Browser.dll"
-a "C:\Users\hornm\.nuget\packages\\0.6.0\lib\netstandard1.0\Microsoft.AspNetCore.Blazor.TagHelperWorkaround.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.entityframeworkcore\2.1.4\lib\netstandard2.0\Microsoft.EntityFrameworkCore.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.entityframeworkcore.abstractions\2.1.4\lib\netstandard2.0\Microsoft.EntityFrameworkCore.Abstractions.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.entityframeworkcore.relational\2.1.4\lib\netstandard2.0\Microsoft.EntityFrameworkCore.Relational.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.entityframeworkcore.sqlserver\2.1.4\lib\netstandard2.0\Microsoft.EntityFrameworkCore.SqlServer.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.caching.abstractions\2.1.1\lib\netstandard2.0\Microsoft.Extensions.Caching.Abstractions.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.caching.memory\2.1.1\lib\netstandard2.0\Microsoft.Extensions.Caching.Memory.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.configuration\2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.configuration.abstractions\2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.configuration.binder\2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.Binder.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.dependencyinjection\2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.dependencyinjection.abstractions\2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.logging\2.1.1\lib\netstandard2.0\Microsoft.Extensions.Logging.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.logging.abstractions\2.1.1\lib\netstandard2.0\Microsoft.Extensions.Logging.Abstractions.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.options\2.1.1\lib\netstandard2.0\Microsoft.Extensions.Options.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.extensions.primitives\2.1.1\lib\netstandard2.0\Microsoft.Extensions.Primitives.dll"
-a "C:\Users\hornm\.nuget\packages\microsoft.jsinterop\0.6.0\lib\netstandard2.0\Microsoft.JSInterop.dll"
-a "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.win32.registry\4.5.0\lib\netstandard2.0\Microsoft.Win32.Registry.dll"
-a "C:\Users\hornm\.nuget\packages\mono.webassembly.interop\0.6.0\lib\netstandard2.0\Mono.WebAssembly.Interop.dll"
-a "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\remotion.linq\2.2.0\lib\netstandard1.0\Remotion.Linq.dll"
-a "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\system.buffers\4.4.0\lib\netstandard2.0\System.Buffers.dll"
-a "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\system.collections.immutable\1.5.0\lib\netstandard2.0\System.Collections.Immutable.dll"
-a "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\system.componentmodel.annotations\4.5.0\lib\netstandard2.0\System.ComponentModel.Annotations.dll"
-a "C:\Users\hornm\.nuget\packages\\4.5.1\lib\netstandard2.0\System.Data.SqlClient.dll"
-a "C:\Users\hornm\.nuget\packages\system.diagnostics.diagnosticsource\4.5.1\lib\netstandard1.3\System.Diagnostics.DiagnosticSource.dll"
-a "C:\Users\hornm\.nuget\packages\system.interactive.async\3.1.1\lib\netstandard1.3\System.Interactive.Async.dll"
-a "C:\Users\hornm\.nuget\packages\system.linq\4.1.0\lib\netstandard1.6\System.Linq.dll"
-a "C:\Users\hornm\.nuget\packages\system.linq.expressions\4.1.0\lib\netstandard1.6\System.Linq.Expressions.dll"
-a "C:\Users\hornm\.nuget\packages\system.linq.queryable\4.0.1\lib\netstandard1.3\System.Linq.Queryable.dll"
-a "C:\Users\hornm\.nuget\packages\system.memory\4.5.1\lib\netstandard2.0\System.Memory.dll"
-a "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\system.numerics.vectors\4.4.0\lib\netstandard2.0\System.Numerics.Vectors.dll"
-a "C:\Users\hornm\.nuget\packages\system.objectmodel\4.0.12\lib\netstandard1.3\System.ObjectModel.dll"
-a "C:\Users\hornm\.nuget\packages\system.reflection.emit\4.0.1\lib\netstandard1.3\System.Reflection.Emit.dll"
-a "C:\Users\hornm\.nuget\packages\system.reflection.emit.ilgeneration\4.0.1\lib\netstandard1.3\System.Reflection.Emit.ILGeneration.dll"
-a "C:\Users\hornm\.nuget\packages\system.reflection.emit.lightweight\4.0.1\lib\netstandard1.3\System.Reflection.Emit.Lightweight.dll"
-a "C:\Users\hornm\.nuget\packages\system.reflection.typeextensions\4.1.0\lib\netstandard1.5\System.Reflection.TypeExtensions.dll"
-a "C:\Users\hornm\.nuget\packages\system.runtime.compilerservices.unsafe\4.5.1\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll"
-a "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\\4.5.0\lib\netstandard2.0\System.Security.AccessControl.dll"
-a "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\\4.5.0\lib\netstandard2.0\System.Security.Principal.Windows.dll"
-a "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\system.text.encoding.codepages\4.5.0\lib\netstandard2.0\System.Text.Encoding.CodePages.dll"
-a "C:\Users\hornm\.nuget\packages\system.threading\4.0.11\lib\netstandard1.3\System.Threading.dll"
-a "C:\Users\hornm\source\repos\WebApplication32\WebApplication32.Shared\bin\Debug\netstandard2.0\WebApplication32.Shared.dll"
-a "C:\Users\hornm\source\repos\WebApplication32\WebApplication32.Client\obj\Debug\netstandard2.0\WebApplication32.Client.dll""
exited with code 1.
WebApplication32.Client C:\Users\hornm\.nuget\packages\\0.6.0\targets\Blazor.MonoRuntime.targets 446

Any direction or assistance would be greatly appreciated.
QuestionError on Build with Latest (as on today 20180812) versions of packages Pin
Member 783241812-Aug-18 18:22
memberMember 783241812-Aug-18 18:22 
AnswerRe: Error on Build with Latest (as on today 20180812) versions of packages Pin
Member 1395821522-Aug-18 10:32
memberMember 1395821522-Aug-18 10:32 
GeneralRe: Error on Build with Latest (as on today 20180812) versions of packages Pin
Member 783241822-Aug-18 12:16
memberMember 783241822-Aug-18 12:16 
GeneralRe: Error on Build with Latest (as on today 20180812) versions of packages Pin
Mike Horn MSU6-Nov-18 8:05
memberMike Horn MSU6-Nov-18 8:05 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun1-Jun-18 10:16
memberHumayun Kabir Mamun1-Jun-18 10:16 
QuestionFew question on blazor Pin
Mou_kol17-May-18 23:19
memberMou_kol17-May-18 23:19 
AnswerRe: Few question on blazor Pin
Carsten V2.018-May-18 0:04
memberCarsten V2.018-May-18 0:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190419.4 | Last Updated 18 May 2018
Article Copyright 2018 by syed shanu
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid