How to Insert Console Application with Entity Framework

Introduction

In this tutorial, we will develop a simple C# console application that we can insert using Entity Framework Core.

Getting Started

In ASP.NET 5 we can create console applications. To create a new console application, first, open Visual Studio 2015. Create the application using File-> New-> Project.

Project

Now we will select the ASP.NET 5 Console Application and click on the OK button.

Console Application

We’re going to use the Entity Framework Designer included as a part of Visual Studio.

Step 1. Click on Project -> Manage NuGet Package.

NuGet Package

Use the below table query to execute any database in the SQL Server.

CREATE TABLE [dbo].[Departments](
    [DeptId] [int] NOT NULL,
      NULL,
    CONSTRAINT [PK_Departments] PRIMARY KEY CLUSTERED 
    (
        [DeptId] ASC
    ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
    
GO
    
CREATE TABLE [dbo].[Employees](
    [EmpId] [int] NOT NULL,
      NULL,
    [DeptId] [int] NULL,
    CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED 
    (
        [EmpId] ASC
    ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

We need to include the following references in our application.

using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

In the main method, I have created 3 classes and 1 method.

Department - To define class members.
Employee - To define class members.
EagerLoadingDbContext - Initialize dB context in the class.
SavedDatabaseOperations - Saved Operation in this method.

Please refer to the code snippet below.

public static void Main(string[] args)
{
    try
    {
        SavedDatabaseOperations();
        Console.Write("Data is saved successfully !");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error:" + ex.Message);
    }
    Console.ReadKey();
}

Initialize the class

The first-class definition of the Department is given below.

public class Department
{
    [Key]
    public int DeptId { get; set; }

    public string DeptName { get; set; }
}

The second-class definition of the Employee is given below.

public class Employee
{
    [Key]
    public int EmpId { get; set; }

    public string EmpName { get; set; }

    public int DeptId { get; set; }
}

The Third-class definition for the EagerLoadingDbContext is given below.

class EagerLoadingDbContext : DbContext
{
    private const string connectionString = "Your own Sql-Server connection string";

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(connectionString);
    }

    public DbSet<Department> Departments { get; set; }

    public DbSet<Employee> Employees { get; set; }
}

Initialize the Method

The method definition for the SavedDatabaseOperations() is given below.

public static void SavedDatabaseOperations()
{
    using (var db = new EagerLoadingDbContext())
    {
        var department = new List<Department>
        {
            new Department { DeptId = 1, DeptName = "IT" },
            new Department { DeptId = 2, DeptName = "HR" },
            new Department { DeptId = 3, DeptName = "Marketing" }
        };

        db.Departments.AddRange(department);

        var employee = new Employee
        {
            EmpId = 1,
            EmpName = "Nirmal",
            DeptId = 1
        };

        db.Employees.Add(employee);

        db.SaveChanges();
    }
}

Click on F5 execute the project and follow the console window. The output will be,

Console window

Output

Summary

I hope this article helps while trying to perform an insert using the Entity Framework Core Data Model. Thanks for reading this article!


Similar Articles