{{announcement.body}}
{{announcement.title}}

Creating a .NET Core 2.1 Class Library Project Using ADO.NET

DZone 's Guide to

Creating a .NET Core 2.1 Class Library Project Using ADO.NET

In this article, we discuss how to create a .NET Core 2.1 Class library project using ADO.NET in order to increase code reusability.

· Web Dev Zone ·
Free Resource

Introduction

In this article, I am going to show you how to create a .NET Core 2.1 Class Library Project using ADO.NET.

This class library project contains business logic functionality for inserting data into a database. Then, I am consuming this class library project in ASP.NET Core 2.1 MVC Application.

We will be using Visual Studio 2017 (version 15.9.13 or above) and SQL Server 2017. You can also use SQL server 2008 or above.

What Is a Class Library?

A class library contains types, classes, interfaces, and methods that are easily reusable, shareable, distributed, or consumed by an application. Also, a class library project is used for code reusability.

Prerequisites

  1. Install Visual studio 2017 Updated version 15.9.13.
  2. Install .Net Core SDK 2.1 or above.
  3. SQL Server 2017.

Now, we will create our .Net Core 2.1 Class library project.

First of all, we will create a database and stored procedures.

You may also like: All Things ASP.NET Core and MVC: Tutorials and Articles.

Creating Database and Stored Procedures

Step 1 - Create a Database

Open your SQL server and use the following script to create the "CoreMvcDB" Database

Create database CoreMvcDB 

Step 2 - Create a Table

Open your SQL Server and use the following script to create the "tbl_Employee" table.

    SQL




    x


     
    1
    create table tbl_Employee
    2
    (
    3
        Sr_no int not null primary key identity(1,1),
    4
        Emp_Name nvarchar(250),
    5
        City nvarchar(100),
    6
        State nvarchar(100),
    7
        Country nvarchar(100),
    8
        Department nvarchar(50)
    9
    )


Step 3 - Create a Stored Procedure

Now, we will create a stored procedure to add Employee data to the database. Open your SQL Server and use the following script to create the procedure.

To insert an Employee Record

SQL




xxxxxxxxxx
1
11


 
1
create procedure sp_Employee_Add
2
@Emp_Name nvarchar(250),
3
@City nvarchar(100),
4
@State nvarchar(100),
5
@Country nvarchar(100),
6
@Department nvarchar(50)
7
AS
8
BEGIN
9
Insert into tbl_Employee(Emp_Name,City,State,Country,Department)
10
values(@Emp_Name,@City,@State,@Country,@Department)
11
END


Now, we will create a .NET Core 2.1 class library project.

Creating a .NET Core 2.1 Class Library Project

Step 1 - Creating a Class Library Empty Solution

First creating an Empty solution for our class library project, it contains our class library project and its related projects. A Visual Studio Solution just serves as a container for one or more projects.

  1. Open Visual Studio menu bar, select File -> New -> Project.
  1. After selecting the project, A "New Project" dialog will open. Expand the “Other ProjectTypes” node and select “Visual Studio Solutions.” Name the Solution “Chittaranjan” and select the OK button.

Step 2 - Creating a .NET Core Class Library Project

  1. In the Solution Explorer, right-click on the Chittaranjan solution file, and from the context menu, select the Add -> New Project menu option.
  1. In the Add New Project dialog, expand the Visual C# node; then, select the .NET Core node in the left side and select the Class Library (.NET Core) project template.

Now, you can give your project a name and select OK to create the .NET Core class library project. Here, my project name is “ChittaDB."

Now, our Class Library project is created. The solution, "Chittaranjan," contains one project, named “ChittaDB.”

Step 3 - Add Class Library Project Functionality

In the “ChittaDB” Class library project, I have added two class files for to insert data and save data in the database. To do this:

  • Add a class in the Class library project.
  • Right-click on the “ChittaDB” project and select the Add a New Item menu option. On the menu option dialog, select VisualC#Items on the left side and select Class on the right-hand side. Then, you can add your class name. Here, the name of our class is EmployeeEntities.cs. Now, select the Add button. This class will contain our Employee properties.
  • Now, open the EmployeeEntities.cs class and put the following code in it. We are also adding the required validators to the fields of EmployeeEntities class, so we need to use System.ComponentModel.DataAnnotations at the top.
    C#




    xxxxxxxxxx
    1
    17


     
    1
    using System.ComponentModel.DataAnnotations;
    2
    namespace ChittaDB
    3
    {
    4
        public class EmployeeEntities
    5
        {
    6
            [Required]
    7
            public string Emp_Name { get; set; }
    8
            [Required]
    9
            public string City { get; set; }
    10
            [Required]
    11
            public string State { get; set; }
    12
            [Required]
    13
            public string Country { get; set; }
    14
            [Required]
    15
            public string Department { get; set; }
    16
        }
    17
    }


  • Add another Class in Class Library Project for Insert Methods.
  • Right-click on the “ChittaDB” project and select add a new Item menu option. On the menu option dialog, Select VisualC#Items in the left side and select Class in the right-hand side. Then you can put your class name. Here Name of our class is EmployeeDBAccessLayer, Select Add button. This class will contain our database related operations.

Now, The Class Library Project structure is given below.

Open EmployeeDBAccessLayer.cs and put the following code to handle the database operations. Make sure to put your connection string.

Note
For Ado.Net, I am adding “Microsoft.EntityFrameworkCore.SqlServer” in my class library project. This is available in Manage NuGet packages.

  1. C#




    xxxxxxxxxx
    1
    35


    1
    using System.Data;
    2
    using System.Data.SqlClient;
    3
    namespace ChittaDB
    4
    {
    5
        public class EmployeeDBAccessLayer
    6
        {
    7
            SqlConnection con = new SqlConnection("put your connection string here");
    8
            public string AddEmployeeRecord(EmployeeEntities employeeEntities)
    9
            {
    10
                try
    11
                {
    12
                    SqlCommand cmd = new SqlCommand("sp_Employee_Add", con);
    13
                    cmd.CommandType = CommandType.StoredProcedure;
    14
                    cmd.Parameters.AddWithValue("@Emp_Name",
    15
                                                employeeEntities.Emp_Name);
    16
                    cmd.Parameters.AddWithValue("@City", employeeEntities.City);
    17
                    cmd.Parameters.AddWithValue("@State", employeeEntities.State);
    18
                    cmd.Parameters.AddWithValue("@Country",
    19
                                                employeeEntities.Country);
    20
                    cmd.Parameters.AddWithValue("@Department",
    21
                                                employeeEntities.Department);
    22
     
                
    23
                    con.Open();
    24
                    cmd.ExecuteNonQuery();
    25
                    con.Close();
    26
     
                
    27
                    return ("Data save Successfully");
    28
                }
    29
                catch (Exception ex)
    30
                {
    31
                    if (con.State == ConnectionState.Open)
    32
                    {
    33
                        con.Close();
    34
                    }
    35
     
                
    36
                    return (ex.Message.ToString());
    37
                }
    38
            }
    39
        }
    40
    }



Step 5 - Build

Build your project by hitting F5 or by selecting the Build menu item in Visual Studio.

Step 6 - Consuming a Class Library Project

Here, I am consuming a class library project in ASP.NET Core 2.1 MVC application. First, we will create an ASP.NET Core 2.1 MVC application.

Open Visual Studio and select File -> New -> Project.

After selecting the project, a New Project dialog will open. Select .NET Core inside the Visual C# menu from the left side panel.

Then, select ASP.NET Core web application from available project templates. Give a name to the project “ChittaWeb” and press OK.

After clicking on the OK button, a new dialog will open to select the project template. You can see two drop-down menus at the top left of the template window. Then, select .NET Core and ASP.NET Core 2.1 from these dropdowns. Select Web application (Model-View-Controller) template and press OK to create the ASP.NET Core MVC project. Then, select the tick mark for configuring for HTTPS.

In Solution, “Chittaranjan” contains two projects; the first project is “ChittaDB.” This is the class library project. The second project name is “ChittaWeb.” This is the ASP.NET Core 2.1 MVC application. Now, our ASP.NET Core MVC application is created.

Now, we can use the .NET Core 2.1 class library functionality in ASP.NET Core 2.1 MVC application.

Step 1 - Add a Class Library Project Reference

To use a class library project in your application, first you must add a reference to the class library project to access its functionality. Right-click on the “ChittaWeb” ASP.NET Core MVC application Dependencies in Solution Explorer and select the Add -> Reference option.

On the next screen, you will see that the ChittaDB is already available. Select ChittaDB and then click the OK button.

Step 2 - Import Namespace and Call Functions

First, add a controller in Asp.Net core MVC application then using Import namespace and call functions.

Right-click on the Controllers folder and select Add New Item.

An Add New Item dialog box will open. Select ASP.NET Core from the left panel; then, select Controller Class from the templates panel, and put make the name EmployeeController.cs. Then, press Add.

In Employeecontroller, I will Import a ChittaDB namespace.

Import Namespace

Before you can use a class library project and its classes, you must import the namespace by using the following code.

using ChittaDB; 

If your class library project reference is added correctly, as soon as you start typing, “using Chitt..”, you will see that Visual Studio Intellisense will load the namespace in the list.

Call Functions

Once the reference is added, all classes, methods, and public members of the class library project should be available in your ASP.NET Core MVC application. Now, we can call all the methods in the Controller.

Here, I will call all the classes and functions from the Class library project. We will put our business logic into this controller.

To handle database operations, we will create an object of EmployeeDBAccessLayer class inside the EmployeeController class.

    C#




    x


     
    1
    using Microsoft.AspNetCore.Mvc;
    2
    using ChittaDB;
    3
    namespace ChittaWeb.Controllers
    4
        {
    5
            public class EmployeeController : Controller
    6
            {
    7
                EmployeeDBAccessLayer empdb = new EmployeeDBAccessLayer();


To handle the business logic of the create operation, open EmployeeController.cs and add the following code into it:

    C#




    xxxxxxxxxx
    1
    31


    1
    using Microsoft.AspNetCore.Mvc;
    2
    using ChittaDB;
    3
    namespace ChittaWeb.Controllers
    4
    {
    5
        public class EmployeeController : Controller
    6
        {
    7
            EmployeeDBAccessLayer empdb = new EmployeeDBAccessLayer();
    8
            
    9
            [HttpGet]
    10
            public IActionResult Create()
    11
            {
    12
                return View();
    13
            }
    14
     
               
    15
            [HttpPost]
    16
            public IActionResult Create([Bind] EmployeeEntities employeeEntities)
    17
            {
    18
                try
    19
                {
    20
                    if (ModelState.IsValid)
    21
                    {
    22
                        string resp = empdb.AddEmployeeRecord(employeeEntities);
    23
                        TempData["msg"] = resp;
    24
                    }
    25
                }
    26
                catch (Exception ex)
    27
                {
    28
                    TempData["msg"] = ex.Message;
    29
                }
    30
                
    31
                return View();
    32
            }
    33
        }
    34
    }


Adding View to the Application

To add views for our controller class, we need to create a folder inside Views folder with the same name as our controller and then add our views to that folder.

Right-click on the Views folder, and then Add >> New Folder and name the folder Employee.

Now, right-click on the Views/Employee folder and then select Add >> New Item.

An Add New Item dialog box will open. Select ASP.NET Core from the left panel, select Razor View from templates panel, and make the name Create.cshtml. Then, press OK.

Create View

This view will be used to Add new employee data to the database.

Open Create.cshtml and put the following code into it.

    HTML




    xxxxxxxxxx
    1
    46


     
    1
    @model ChittaDB.EmployeeEntities
    2
    @{
    3
    ViewData["Title"] = "Create Employee";
    4
    }
    5
    <h2>Create Employee</h2>
    6
    <hr />
    7
    <form asp-action="Create" class="form-horizontal">
    8
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    9
    <div class="form-group">
    10
    <label class="control-label">Name</label>
    11
    <input asp-for="Emp_Name" class="form-control" />
    12
    <span asp-validation-for="Emp_Name" class="text-danger"></span>
    13
    </div>
    14
    <div class="form-group">
    15
    <label class="control-label">City</label>
    16
    <input asp-for="City" class="form-control" />
    17
    <span asp-validation-for="City" class="text-danger"></span>
    18
    </div>
    19
    <div class="form-group">
    20
    <label class="control-label">State</label>
    21
    <input asp-for="State" class="form-control" />
    22
    <span asp-validation-for="State" class="text-danger"></span>
    23
    </div>
    24
    <div class="form-group">
    25
    <label class="control-label">Country</label>
    26
    <input asp-for="Country" class="form-control" />
    27
    <span asp-validation-for="Country" class="text-danger"></span>
    28
    </div>
    29
    <div class="form-group">
    30
    <label class="control-label">Department</label>
    31
    <input asp-for="Department" class="form-control" />
    32
    <span asp-validation-for="Department" class="text-danger"></span>
    33
    </div>
    34
    <div class="form-group">
    35
    <input type="submit" value="Submit" class="btn bg-primary" />
    36
    </div>
    37
    </form>
    38
    @{
    39
    if (@TempData["Msg"] != null)
    40
    {
    41
    <script>
    42
    alert('@TempData["msg"]')
    43
    </script>
    44
    }
    45
    }
    46
     
               



Add a New Item

Edit the Views/Shared/_Layout page and add a new menu, Add Employee. For that, add the following code:

    HTML




    xxxxxxxxxx
    1


     
    1
    <ul class="nav navbar-nav">
    2
    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
    3
    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
    4
    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
    5
    <li><a asp-area="" asp-controller="Employee" asp-action="Create">Add Employee</a></li>
    6
    </ul>


Build and Run

Now press F5 to launch the application or run the application. Click on Add Employee to navigate to the Create view.

We have also added validation using DataAnnotations on the Create View page. If we miss the data in any field while creating an employee record, we will get a required field validation error message.

When the data is saved, the success message will show. From there, click ok. After the data is saved, you can check your database.

Conclusion

In this article, you have learned how to create a .NET Core 2.1 Class library project using ADO.NET with the help of Visual Studio 2017. You have also learned how to consume a .NET Core class library in an ASP.NET Core MVC application for insert data.


Further Reading

Topics:
.net core ,web dev ,c# ,class library ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}