How to Build a CRUD Application with ASP.NET Core 3.0 & Entity Framework 3.0 Using Visual Studio 2019

In this blog, I am going to provide a walk-through on developing a web application using ASP.NET Core 3.0, connecting it to a database (database-first) using the Entity Framework Core 3.0 command, and performing CRUD operations using scaffolding (code generator). I am going to develop a sample application for inventory management with basic operations.

ASP.NET Core is a web framework from Microsoft. It is an open-source, cross-platform, cloud-optimized web framework that runs on Windows using .NET Framework and .NET Core, and on other platforms using .NET Core. It is a complete rewrite that unites ASP.NET MVC and Web API into a single programming model and removes system-related dependencies. This helps in deploying applications to non-Windows servers and improves performance.

This blog post will discuss the following:

Note: In this demo application, I have used ASP.NET Core 3.0 Preview 8, Entity Framework Core 3.0 Preview 8, with Visual Studio 2019 16.3.0 Preview 2.0.

Prerequisites

A .NET Core application can be developed using these IDEs:

  • Visual Studio
  • Visual Studio Code
  • Command Prompt

Here, I am using Visual Studio to build the application. Be sure that the necessary software is installed:

  • Visual Studio 2019 16.3.0 Preview 2.0
  • NET Core 3.0 Preview 8
  • SQL Server 2017

Create database

Let’s create a database on your local SQL Server. I hope you have installed SQL Server 2017 in your machine (you can use SQL Server 2008, 2012, or 2016, as well).

Step 1: Open Visual Studio 2019.

Step 2: Open SQL Server Object Explorer and click Add SQL Server.Adding SQL Server

Adding SQL Server

Step 3: Here we have an option to choose from the local machine’s SQL Server, connected via network, and the Azure SQL database. I have chosen the local SQL Server instance. I provide the SQL Server details and click Connect. The SQL Server will be listed in Explorer.Establishing connection to the database server

Establishing connection to the database server

SQL Server listed in Solution Explorer

SQL Server listed in Solution Explorer

Step 4: Right-click on a database node and create a new database (Inventory).

Step 5: Now we have the database in place. Click on our database and choose New Query.

Step 6: For this application, I am going to create a table called Products with basic attributes. Paste the following SQL query into the Query window to create a Products table.

Create Table Products(
ProductId BigInt Identity(1,1) Primary Key,
Name Varchar(100) Not Null,
Category Varchar(100),
Color Varchar(20),
UnitPrice Decimal Not Null,
AvailableQuantity BigInt Not Null,
CratedDate DateTime Default(GetDate()) Not null)

Step 7: Click the Run icon to create the table. Now we have the table needed for our application.

Create an ASP.NET Core application

Follow these steps to create an ASP.NET Core application.

Step 1: In Visual Studio 2019, click on File -> New -> Project.

Step 2: Choose the Create a new project option.

Step 3: Select the ASP.NET Core Web Application template. Creating new ASP.NET Core project

Step 4:  Enter project name and click Create.Configuring the project

Step 5: Select .NET Core and ASP.NET Core 3.0 and choose the Web Application (Model-View-Controller) template.

Uncheck the Configure for HTTPS under the Advanced options (in a development environment, we have no need of SSL).

Click Create. Then the sample ASP.NET Core application will be created with this project structure.Configuring the project

Install NuGet packages

The following NuGet packages should be added to work with the SQL Server database and scaffolding. Run these commands in Package Manager Console:

  • Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design -Version 3.0.0-preview8-19413-06 This package helps generate controllers and views.
  • Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.0.0-preview8.19405.11 This package helps create database context and a model class from the database.
  • Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.0.0-preview8.19405.11 The database provider allows Entity Framework Core to work with SQL Server.

Scaffolding

ASP.NET Core has a feature called scaffolding, which uses T4 templates to generate code of common functionalities to help keep developers from writing repeat code. We use scaffolding to perform the following operations:

  • Generate entity POCO classes and a context class for the database.
  • Generate code for create, read, update, and delete (CRUD) operations of the database model using Entity Framework Core, which includes controllers and views.

Connect application with database

Run the following scaffold command in Package Manager Console to reverse engineer the database to create database context and entity POCO classes from tables. The scaffold command will create POCO class only for the tables that have a primary key.

Scaffold-DbContext “Server=ABCSERVER;Database=Inventory;Integrated Security=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

  • Connection—Sets connection string of the database.
  • Provider—Sets which provider to use to connect database.
  • OutputDir—Sets the directory where the POCO classes are to be generated.

In our case, the Products class and Inventory context class will be created.Product and Inventory class in the project

Open the Inventory Context class file. You will see the database credentials are hard coded in the OnConfiguring method.

It’s not good practice to have SQL Server credentials in C# class, considering the security issues. So, remove this OnConfiguring method from context file.OnConfiguring method

And move the connection string to the appsettings.json file.Connection string moved to appsettings

Then we can register the database context service (InventotyContext) during application startup. In the following code, the connection string is read from the appsettings file and passed to the context service.Configuring services

Then this context service is injected with the required controllers via dependency injection.

Perform CRUD operations

Now we set up the database and configure it to work with Entity Framework Core. We’ll see how to perform CRUD operations.

Right-click on the controller folder, select add new item, and then select controller. Then this dialog will be displayed.Adding MVC Controller with views

Select the MVC Controller with views, using Entity Framework option and click Add.

We need to choose a database model class and data context class, which were created earlier, and click Add.Adding model and context class

That’s it, we’re done. The scaffolding engine uses T4 templates to generate code for controller actions and views in their respective folders. This is the basic version of code; we can modify it as needed.

Please find the files created,Created class listed in the project

Now we have fully functional CRUD operations on the Products table.

Then, change the default application route to load the Products Controller instead of the home controller. Open the Startup.cs file and under the Configure method, change the default controller to Products.Updating startup page

With the help of the scaffolding engine, developers need not write CRUD operations for each database model.

Run application

Click Run to view the application. A new browser tab will open and we’ll be able to see the product listing page. Since there is no product in the inventory, it’s empty.Empty Product Listing

Click Create New to add new products to the inventory.Adding new product to inventory

After entering the details, click Create. Now we should see newly created products in the listing page as in the following screenshot. I have added three more products.Product Listing - updated

Click Details to view the product details.Details of the product

Click Edit to update product details.Editing the product

Click Delete to delete a product. Confirmation will be requested before it’s deleted from the database.Deleting the product

Without writing a single line of code, we are able to create an application with basic CRUD operations with the help of the scaffolding engine.

I have shared the sample application in this GitHub location. Extract the application, change the connection string in the appsettings.json file that points to your SQL Server, and run the application.

Conclusion

In this blog, we have learned how to create an ASP.NET Core application and connect it to a database to perform basic CRUD operations using Entity Framework Core 3.0 and a code generation tool. I hope it was useful. Please share your feedback in the comments section below.

The Syncfusion ASP.NET Core UI controls library is the only suite that you will ever need to build an application since it contains over 65 high-performance, lightweight, modular, and responsive UI controls in a single package. Download our free trial from here. You can also explore our online demos here.

If you have any questions or require clarifications about these controls, please let us know in the comments below. You can also contact us through our support forumDirect-Trac, or feedback portal. We are happy to assist you!

Tags:

Share this post:

Related Posts

Comments (23)

[…] How to Build a CRUD Application with ASP.NET Core 3.0 & Entity Framework 3.0 using Visual Studio… (Kannan Eswar) […]

Good article, but since we’re here for Syncfusion, it would be nice to show how to use Syncfusion controls in the data entry forms or how the Syncfusion scaffolding process for grid (say) works with Entity Framework. Any chance of an update or a new article?

Hi Grahame,

Thanks for your feedback. You can find more details about how to use Essential JS 2 form controls for ASP.NET Core in the below link,

https://ej2.syncfusion.com/aspnetcore/TextBoxes/DefaultFunctionalities#/material

Currently we doesn’t support scaffolding for ASP.NET Core. We already planned to provide scaffolding support for ASP.NET Core and will be released in our future release. Once we release we will update you.

Thanks,
Kannan Eswar.

Thank you for article. Scaffolding is a quick way to create code, but it violates the SOLID principle. It is better to use repository pattern and inject dependencies. Unfortunately, such a code generator does not have in VS 🙁

Next thing, a better way, more efficient is use to AddDbContextPool method:
~~~
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool(options => options.UseSqlServer(connectionString));
}
~~~

Regards,
Marcin

Hi Marcin Sulecki,

Yes, VS Scaffolding is starting point to work with ASP.NET Core application with database. In upcoming blog I will write about how to use repository pattern and dependency injection to connect with database.

You have pointed correctly AddDbContextPool gives better performance since it shares the context instance instead of creating new context instance for every request.

Thanks,
Kannan Eswar.

Thank you for this brilliant article, I need exactly this to start a new project.

Hi Zsolt Hunyadi,

I am glad to hear that this blog helped you.

Thanks,
Kannan Eswar.

Can this app be easily deployed on Azure free plan?

Hi UROSP,

Support of deploying ASP.NET Core 3.0 application to Azure App service is not available yet.

But we can deploy to Azure app service by following one of the approach mentioned in the link below,

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/azure-apps/?view=aspnetcore-3.0&tabs=visual-studio#deploy-aspnet-core-30-to-azure-app-service

Thanks,
Kannan Eswar.

Thanks for a good intro.
But using BigInt for product id and quantity seems a bit excessive …

Hi Gustav Brock,

Thanks for your feedback.

Yes, you are correct datatype selection depends on the each application need. For the demo purpose I have used BigInt instead of Int.

Thanks,
Kannan Eswar.

Hi,

I would like to know how I call out multiple tables with connected ID’s in ASP.NET Core 3.0 ?

Hi SIIM,

In this blog, I have used Scaffolding support to implement the basic level of database queries using Entity Framework.

In below you can find more details about how to join different tables and obtain the result,

I hope you have downloaded the Inventory application attached to this blog. Please follow the below steps,

Step 1:

For example, consider you have the below two tables and add some dummy data.

Create table Region (
RegionId int identity(1,1) primary key,
RegionName varchar(100) Not null,
RegionManagerEmail varchar(100) Not null)

Create table Store (
StoreId int identity(1,1) primary key,
RegionId int FOREIGN KEY REFERENCES Region(RegionId) not null,
StoreName varchar(100) Not null,
StoreManagerEmail varchar(100) Not null,
Location varchar(max))

insert into Region (RegionName, RegionManagerEmail)
values (‘Africa’, ‘AfricaRegion@abc.com’), (‘Asia’, ‘AsiaRegion@abc.com’),(‘Europe’, ‘EuropeRegion@abc.com’),
(‘North America’, ‘NorthAmericaRegion@abc.com’), (‘Sotuh America’, ‘SotuhAmericaRegion@abc.com’),(‘Australia’, ‘AustraliaRegion@abc.com’)

insert into Store (StoreName, StoreManagerEmail, RegionId, Location)
Values (‘Store 1’, ‘Store1@abc.com’, 2, ‘Location A’), (‘Store 2’, ‘Store2@abc.com’, 2, ‘Location B’), (‘Store 3’, ‘Store2@abc.com’, 2, ‘Location C’),
(‘Store 1’, ‘Store1@abc.com’, 1, ‘Location A’), (‘Store 2’, ‘Store2@abc.com’, 1, ‘Location B’), (‘Store 3’, ‘Store2@abc.com’, 1, ‘Location C’)

Step 2:

Paste the below code into Package Manager Console and run, which will auto-generate entity POCO classes from the above two tables and entity will be added into inventory context file,

Scaffold-DbContext “Server=ABCSERVER;Database=Inventory;Integrated Security=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force

Step 3:

Add new MVC Empty Controller called Store and add the necessary dependencies, in our case add Inventory context as below,

public class StoreController : Controller
{
private readonly InventoryContext _context;

public StoreController(InventoryContext context)
{
_context = context;
}
}

Step 4:

Now it’s time to write LINQ query to join the two tables and retrieve the result. In this example, I am going to write a method which returns all the stores belongs to a particular region.

public async Task<List> GetStoreByRegionId(int regionId)
{
var stores = await (from store in _context.Store
join region in _context.Region on store.RegionId equals region.RegionId
where region.RegionId == regionId
select store).ToListAsync();

return stores;
}

Here I have used LINQ Query Expression method to join Store and Region tables and retrieving the result.

Step 5:

Load the below URL in your browser,

http://localhost:54360/Store/GetStoreByRegionId?regionId=1

And you able to view stores filtered by given regionId,

[{“storeId”:4,”regionId”:1,”storeName”:”Store 1″,”storeManagerEmail”:”Store1@abc.com”,”location”:”Location A”,”region”:null},{“storeId”:5,”regionId”:1,”storeName”:”Store 2″,”storeManagerEmail”:”Store2@abc.com”,”location”:”Location B”,”region”:null},{“storeId”:6,”regionId”:1,”storeName”:”Store 3″,”storeManagerEmail”:”Store2@abc.com”,”location”:”Location C”,”region”:null}]

Note: localhost port number may be varied in your development machine.

Please refer the below link to know more about LINQ Query,

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/basic-linq-query-operations

Thanks,
Kannan Eswar.

Hope the article helps the freshers and new joinee’s like me.
thanks Eswar , keep spreading knowledge..

Hi Manikandan Pandian,
Yes sure, thanks for your feedback.
Thanks,
Kannan Eswar.

Hi, thanks for your article…. I learnt a lot.

I tried to follow the steps and when I try to create the controller. I got the following error
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

I would like to ask how I could solve it.

Thank you.

Hi GEORGE,

Thanks for your feedback.

Error conveys that DbContext was not configured correctly. Could you please ensure the below steps to confirm DbContext is configured correctly before creating controller?

1. In context file, ensure our DbContext accepts InventoryContext object in its constructor and passes it to the base constructor.

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

2. Below code should be removed from Context file.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#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=synclapn18531;Database=Inventory;Integrated Security=True”);
}
}

3. And move the connection string to the appsettings.json file.
“ConnectionStrings”: {
“InventoryDatabase”: “Server=*******;Database=Inventory;Trusted_Connection=True;”
}

Note: Here provide appropriate connection string based on your database server.

4. Then register the database context service (InventotyContext) during application startup. In the following code, the connection string is read from the appsettings file and passed to the context service.
var connection = Configuration.GetConnectionString(“InventoryDatabase”);
services.AddDbContext(options => options.UseSqlServer(connection));

5. Now try to create scaffold controller.

Thanks,
Kannan Eswar.

Dear Kannan, thank you for the article, it is very useful to newbie like me, however, I encountered the same error, can you be more explicit with instruction number 4. I have tried to put the code in startup.cs but it gave coding error.
This is the previous code in the startup.cs:
public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())

and this is new with the error:
public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var connection = Configuration.GetConnectionString(“InventoryDatabase”);
services.AddDbContext(options => options.UseSqlServer(connection));

services.AddControllersWithViews();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())

Below is the coding error:
The type or namespace name ‘InventoryContext’ could not be found (are you missing a using directive or an assembly reference?)
‘DbContextOptionsBuilder’ does not contain a definition for ‘UseSqlServer’ and no accessible extension method ‘UseSqlServer’ accepting a first argument of type ‘DbContextOptionsBuilder’ could be found (are you missing a using directive or an assembly reference?)

Kindly help, as usual, thank you.

Hi ABBEY,

Thanks for your feedback. The reported errors are due to reference missing.

ERROR 1: THE TYPE OR NAMESPACE NAME ‘INVENTORYCONTEXT’ COULD NOT BE FOUND (ARE YOU MISSING A USING DIRECTIVE OR AN ASSEMBLY REFERENCE?)

In this demo application context name is InventoryContext, (if your context name is different, please update that context name here)

services.AddDbContext<InventoryContext > (options => options.UseSqlServer(connection));

You have to add namespace of context file in Startup.cs as below

using InventoryManagement.Models;

ERROR 2: ‘DBCONTEXTOPTIONSBUILDER’ DOES NOT CONTAIN A DEFINITION FOR ‘USESQLSERVER’ AND NO ACCESSIBLE EXTENSION METHOD ‘USESQLSERVER’ ACCEPTING A FIRST ARGUMENT OF TYPE ‘DBCONTEXTOPTIONSBUILDER’ COULD BE FOUND (ARE YOU MISSING A USING DIRECTIVE OR AN ASSEMBLY REFERENCE?)

You have add namespace of ‘USESQLSERVER’ in Startup.cs as below,

using Microsoft.EntityFrameworkCore;

———————————————————————————————
Th final namespace reference of Startup.cs class as below,

using InventoryManagement.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Thanks,
Kannan Eswar.

Dear Kannan,

Much appreciation for the error correction. The code was subsequently concluded and run successfully.
Cheers!

Hello, How are you?
Could show me, please, how tu use “Entity Framework” and “MVC Controller with views, using Entity Framework” with SyncFusion DataGrid in ASP NET Core?
What I need is operate on MS SQL Server database – CRUD – with DataGrid.

Have a nice day
Mario

Hi Mario,

Thanks for contacting syncfusion support

CRUD operations are require remote data binding. We used the UrlAdaptor to access the remote data. Refer to the following Help Document for the CRUD Actions.

Documentation link : https://ej2.syncfusion.com/aspnetcore/documentation/grid/edit/?no-cache=1#url-adaptor

A sample with entity framework is attached below which covers the remote binding with the CRUD actions.

Sample : https://www.syncfusion.com/downloads/support/forum/148512/ze/Sample_CRUD_SQL_CORE-1121156690.zip

Code Snippet :

For Insert operation :

HomeController.cs

public async Task Insert([FromBody]CRUDModel param)
{
_context.Orders.Add(param.Value);
await _context.SaveChangesAsync();
return Json(param.Value);

}

For Update operation :

HomeController.cs

public async Task Update([FromBody]CRUDModel param)
{
_context.Orders.Update(param.Value);
await _context.SaveChangesAsync();
return Json(param.Value);
}

For Delete operation :

HomeController.cs

public async Task Delete([FromBody]CRUDModel param)
{
Orders value = _context.Orders.Where(e => e.OrderID == Int32.Parse(param.Key.ToString())).FirstOrDefault();
_context.Remove(value);
await _context.SaveChangesAsync();
return Json(value);
}

Index.cshtml

<ejs-grid id="Grid" allowPaging="true" height="300" toolbar="@(new List() {“Add”, “Edit”, “Update”, “Delete” })”>

Please get back to us if you need further assistance

Regards,
Maithiliy K

Nice post, I’ve bookmarked this. I had to write an Azure Core WebApp exactly like this a few months ago and struggled through a lot of what you describe clearly here – I could have done with this then! Keep up the good work 🙂

Leave a comment