Basic terms of RESTful web API

Idempotent :

GET is idempotent because every time it returns a fixed or same result.
PUT is also idempotent because it can update multiple times and return the same result every time.
POST is not idempotent because every time it creates new item and return different item.
DELETE is not idempotent because after deleting an item it will return null for that same item.

Source Link : http://www.restapitutorial.com/lessons/idempotency.html
Source video : https://www.youtube.com/watch?time_continue=246&v=6dVNdFwqeKs

Code first procedure in Entity Framework Core (Part 1)

Here I am going to show in step by step how to make database using Entity framework core (Code first) :

Step 1 (Create project):
Create a new console application. Give the project a name. I give my project name “FECore001”.

Step 2 (Add library):
Now add new class library in the project like below and remove class1.cs :

now my project looks like below :

Step 3 (Create classes):

Now create three class named “School”, “Teacher” and “Student” in “FECore001.MyClassLibrary” library.

Lets consider School and Teacher have one to many relation,
and Teacher and Student have one to many relation.

School Class :

public class School
{
public School()
{
Teachers = new List<Teacher>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime StartDate { get; set; }
public List<Teacher> Teachers { get; set; }
}

Teacher Class :

public class Teacher
{
public Teacher()
{
Students = new List<Student>();
}
public int Id { get; set; }
public string Name { get; set; }
public School School { get; set; }
public int SchoolId { get; set; }
public List<Student> Students { get; set; }
}

Student Class :

public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public Teacher Teacher { get; set; }
public int TeacherId { get; set; }
}

Step 4 (Add EntityFrameworkCore NuGet Package): 

Now I am going to add EntityFarmeworkCore in this project using NuGet Package:
Right click on “FECore001.MyClassLibrary” and select “Manage NuGet Packages”.

 

Select browse.
Then Search item “Microsoft.EntityFrameworkcore.sqlserver”.
Then click install.

Same as install “Microsoft.EntityFrameworkcore.tools”.

After installing this package we can see all the packages are install under reference that we need for entity framework core.

Step 5 (Create MyContext class) :

       using Microsoft.EntityFrameworkCore;

namespace FECore001.MyClassLibrary
{
public class MyContext : DbContext
{
public DbSet<School> Schools { get; set; }
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Student> Students { get; set; }
}
}

Step 6 (Add connection string in MyContext class) :

Add below override method in MyContextClass.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(“Data Source=.;Initial Catalog=MySchool;Integrated                                                                                Security=True”);
}

Here my database name will be MySchool after migrate my code.

Step 7 (Migration) :

Now I am going to add a migration that make relation between entities.
Select tools => NuGet Package Manager => package manager console. Like below :

Now set “FECore001.MyClassLibrary” as start up project and select project name and write “add-migration Initial” like below image :

Now click enter.
Now we can see a folder named “Migrations” and two classes under it.

Now open “20170407164404_Initial” where we can see migration detail and in “MyContextModelSnapshot” we can see mapping.

Step 8 (Create Database) : 
Now we are going to create database. in comman shell write “update-database -verbose” add press enter.

Now open sql server and see that “MySchool” database is created.

 

Done. Thanks for reading. 🙂

CRUD Operation using Entity framework core – Code first procedure (Part -2)

Here I am going to show CRUD operation using entity framework core (Code first procedure).

Step 1 (Create project):

Create a project named “CRUD_EFCore”.

Step 2 (Install NuGet Packages) :

Right click on project name and select “Manage NuGet Packages”.
Browse “Microsoft.EntityFrameworkcore.sqlserver and install it.

Same as install package “Microsoft.Entityworkcore.tools”.

Step 3 (Create a Object) :

Lets create a class named “Student.cs”.

public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Roll { get; set; }
}

Step 4 (Create context class) :

Create a context class named “StudentContext.cs”.

using Microsoft.EntityFrameworkCore;

public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(“Data Source=.;Initial Catalog=DB_Student;Integrated Security=True”);
}
}

Step 5 (Add migration) :

Now I am going to add a migration.
Select tools => NuGet Package Manager => Package manager console.
Type add-migration firstMigration like below and press enter.

After doing successfully migration, we can see a Migrations folder and two classes automatically created under project.

Step 6 (Create database) :

Now we are going to create database. In command shell write “update-database -verbose” like below and press enter.

After done, open Sql server and see database part. We can see a database automatically created named “DB_Student”.

Basic set up is done. How CRUD part is start from below.

Step 7 (Create operation) :

Open Program.cs class.

private static StudentContext _context = new StudentContext();
private static void Main(string[] args)
{
CreateStudent();
}

private static void CreateStudent()
{
var student = new Student { Name = “Rahat”, Roll = “001” };
_context.Students.Add(student);
_context.SaveChanges();
}

Now run the project.
Output :



Step 8 (Retrieve operation) :

        private static StudentContext _context = new StudentContext();
private static void Main(string[] args)
{
//CreateStudent
RetrieveStudent();
}

private static void RetrieveStudent()
{
var students = _context.Students.ToList();
foreach (var student in students)
{
Console.WriteLine(student.Name + “,”);
Console.ReadLine();
}
}

Run the project.
Output :

Step 9 (Update operation) :

        private static StudentContext _context = new StudentContext();
private static void Main(string[] args)
{
//CreateStudent
//RetrieveStudent();
UpdateStudent();
}

private static void UpdateStudent()
{
var student = _context.Students.FirstOrDefault();
student.Name = “Sabbir”;
_context.SaveChanges();
}

Run the project.

Output :

Step 10 (Delete operation) :

        private static StudentContext _context = new StudentContext();
private static void Main(string[] args)
{
//CreateStudent
//RetrieveStudent();
//UpdateStudent();
DeleteStudent();
}

private static void DeleteStudent()
{
var student = _context.Students.FirstOrDefault(s => s.Name == “Sabbir”);
_context.Students.Remove(student);
_context.SaveChanges();
}
Run the project.
Output :

Done. 🙂

Add database connection string in asp.net core using entity framework core (8 Steps)

Here I am going to show in step by step how to set connection string of database in asp.net core project using entity framework core.
 
Step 01 (Create project):
Create an asp.net core web application named “EmployeeProject”. Press Ok.
 
 
 
Now select web application and click on ok.
 
Step 02 (Create object class):
Create a folder named “Models” and create a object class named “Employee.cs”.
 
 
 
 
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
 
 public class Employee
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public string Designation { get; set; }
        public string Skills { get; set; }
        public int ProjectId { get; set; }
    }
 
Step 3 (Create context class) :
 
Create a context class named “EmployeeContext.cs” under models folder.
 
    using Microsoft.EntityFrameworkCore;
 
    public class EmployeeContext : DbContext
    {
        public EmployeeContext(DbContextOptions<EmployeeContext> options) : base(options)
        {
        }
 
        public DbSet<Employee> Employee { get; set; }
    }
 
 
Step 4 (Add NuGet Packages) :
 
Open “project.json”.
 
Add 3 NuGet Packages in “dependencies” part of project.json file like below.
 
1. Microsoft.EntityFrameworkCore
2. Microsoft.EntityFrameworkCore.SqlServer
3. Microsoft.EntityFrameworkCore.Tools
 
 
 
Add “Microsoft.EntityFrameworkCore.Tools” in tools part.
 

Step 5 (Add Services) :

Open Startup.cs class, and modify ConfigureServices method.

        public void ConfigureServices(IServiceCollection services)
        {
            //Register Context with dependency Injection
            var configurationSection = Configuration.GetSection(“ConnectionStrings:DefaultConnection”);
            services.AddDbContext<EmployeeContext>(options => options.UseSqlServer(configurationSection.Value));

            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddMvc();

        }



Step 6 (Add connection string) :
 
Open “appsettings.json”.
 
 
 

Step 7 (Add migration) :

Now I am going to add a migration,Select tools => NuGet Package Manager => Package manager console. Like Below :







Write add-migration firstMigration and click enter.










 
After migration done we can see a migration folder and class like below.
 
 
 
Step 8 (Create database) :
 
Now right “update-database -verbose” but press enter.
 
 
 
After “done” this operation, open SQL server and we will see a database named “Employee_AspDotNetCore” created.
 
 

Many to many relation using Entity Framework Core (Code first)

Here I am going to show step by step – how to create many to many relation using Entity Framework Core.

Step 1 (Create a console application) :

Create a console application named “Many_2_Many_FECore”.

Step 2 (Create classes) :

Lets create two classes named “Teacher” and “Student”, using this two classes I will make many to many relation.

Teacher.cs :

public class Teacher
{
public Teacher()
{
TeacherStudents = new List<TeacherStudent>();
}

public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
public List<TeacherStudent> TeacherStudents{ get; set; }
}

Student.cs :

public class Student
{
public Student()
{
TeacherStudents= new List<TeacherStudent>();
}

public int Id { get; set; }
public string Name { get; set; }
public string Roll { get; set; }
public List<TeacherStudent> TeacherStudents{ get; set; }
}

Now I am going to take another class for many to many relation named “TeacherStudent”.

TeacherStudent.cs :

public class TeacherStudent
{
//See TeacherStudent has no primary key, 
        //but Entity Framework Core wants primary key for this class. I will discuss letter how can        // we solve this.

public int TeacherId { get; set; }
public Teacher Teacher { get; set; }
public int StudentId { get; set; }
public Student Student { get; set; }
}

Step 3 (Add NuGet Packages) :

Right click on project name add select “Manage NuGet Packages” then we can see below window.
Search “Microsoft.EntityFrameworkcore.sqlserver” and click install button. After accept licensee it will install automatically.

Same as install “Microsoft.EntityFrameworkcore.tools” package.

Step 4 (Create context class) :

Create a class named ‘MyContext”.

MyContext.cs :

public class MyContext : DbContext
{
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Student> Students { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//This line use to avoid primary key of TeacherStudent table
modelBuilder.Entity<TeacherStudent>().HasKey(s => new { s.StudentId, s.TeacherId });

            base.OnModelCreating(modelBuilder);
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//New created database name will be DbTeacherStudent
optionsBuilder.UseSqlServer(“Data Source=.;Initial Catalog=DbTeacherStudent;Integrated Security=True”);
}
}

Step 5 :

Now I am going to add a migration,
Select tools => NuGet Package Manager => Package manager console. Like Below :

write add-migration myMigration and click entry.

After that we will see below “Migration” folder.

Step 6 :

Migration done but database is not create yet. To create database we need to write below text and click enter :

“update-database -verbose”

After operation will done, open SqlServer and we will see a new database named “DbTeacherStudent”

Done. 🙂