Adding items to the database

In this part of the demonstration, we are going to add an employee to the database. First, we need to create an Employee class that represents the objects we are going to store in the container. You can create an item using the CreateItem method, as follows:

  1. Add a new class to the project, and call it Employee.cs.
  2. Replace the references with the following (you should be prompted to install the NuGet package for this; if not, open the NuGet package manager and add it manually):
using Newtonsoft.Json;
using System;
  1. Then, add the following code, to create the Employee class:
    public class Employee
{
public int EmployeeID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Title { get; set; }
public DateTime? BirthDate { get; set; }
public DateTime? HireDate { get; set; }
}
  1. In Program.cs, add the following code, to create a new employee object before the Main method:
  static Employee NewEmployee = new Employee
{
FirstName = "Sjoukje",
LastName = "Zaal",
Title = "Mrs",
BirthDate = new DateTime(1979, 7, 7),
HireDate = new DateTime(2020, 1, 1)
};
  1. In Program.cs, add the AddItemsToDatabase method after your GetStartedDemo method. Then, add the following code, to add the new employee to the database. First, create the connection, and create the query, as follows:
   static void AddItemsToDatabase()
{
connection = new SqlConnection(connectionstring);

using (connection)
{
try
{
Console.WriteLine(" Create a new employee:");
Console.WriteLine("========================================= ");

var cmd = new SqlCommand("Insert Employee (FirstName, LastName, Title, BirthDate, HireDate) values (@FirstName, @LastName, @Title, @BirthDate, @HireDate)", connection);
cmd.Parameters.AddWithValue("@FirstName", NewEmployee.FirstName);
cmd.Parameters.AddWithValue("@LastName", NewEmployee.LastName);
cmd.Parameters.AddWithValue("@Title", NewEmployee.Title);
cmd.Parameters.AddWithValue("@BirthDate", NewEmployee.BirthDate);
cmd.Parameters.AddWithValue("@HireDate", NewEmployee.HireDate);
  1. Then, open the connection, execute the query, and close the connection, as follows:
                    connection.Open();
cmd.ExecuteNonQuery();
connection.Close();

Console.WriteLine(" Finsihed Creating a new employee:");
Console.WriteLine("========================================= ");
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
}
}
  1. Finally, we need to call AddItemsToDatabase in the GetStartedDemo method again, as follows:
 static void GetStartedDemo()
{
connectionstring = "<replace-with-your-connectionstring>";

//ADD THIS PART TO YOUR CODE
AddItemsToDatabase();
}

In this part of the demonstration, we have added some items to the database. In the next part, we will query the database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.54.245