In this tutorial you will learn to Insert Records in Database with Entity Framework Core. EF Core executes Insert Operation for the entities whose EntityState is set to ‘Added’.
There are 2 entities which are Department & Employee. A Department entity can have more than one Employee so there is many-to-one relationship between them.
So create 2 classes for these 2 entities. Create Models folder on the root of the application and add a class called Employee.cs inside it. It’s code is given below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CRUD.Models
{
public class Employee
{
public int Id { get; set; }
public int DepartmentId { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
public Department Department { get; set; }
}
}
public Department Department { get; set; }
which is a Navigation Property as it references the related Department entity.Next add Department.cs class inside the Models folder with the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CRUD.Models
{
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Employee> Employee { get; set; }
}
}
public ICollection Employee { get; set; }
which is a Navigation Property as it references the related Employee entity. To be more exact specific it is the Collection Navigation Property as it contains references to many related Employee entities.Now add the Database Context file named CompanyContext.cs in the Models folder. It’s code is given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace CRUD.Models
{
public class CompanyContext : DbContext
{
public DbSet<Department> Department { get; set; }
public DbSet<Employee> Employee { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(@"Server=vaio;Database=Company;Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>(entity =>
{
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false);
});
modelBuilder.Entity<Employee>(entity =>
{
entity.Property(e => e.Designation)
.IsRequired()
.HasMaxLength(25)
.IsUnicode(false);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false);
entity.HasOne(d => d.Department)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.DepartmentId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Employee_Department");
});
}
}
}
.WithMany(p => p.Employee)
on line no 45 makes the many-to-one relationship between the 2 database tables.Finally run the Entity Framework Core Migrations to create the database and tables from the DbContext class. These migrations are given below:
PM> dotnet ef migrations add Migration1
PM> dotnet ef database update
The database will be created in SQL Server and now we are ready to move forward.
First let me show how to Insert a record on the Department table.
using (var context = new CompanyContext())
{
var dept = new Department()
{
Name = "Designing"
};
context.Entry(dept).State = EntityState.Added;
context.SaveChanges();
}
I have created a new Designing object of the Department class and set its EntityState to Added.
When the DbContext.SaveChanges() method is called this new record is inserted on the Department table.
There is also a shorter way to insert a record. The below code will do the same thing.
var dept = new Department()
{
Name = "Designing"
};
using (var context = new CompanyContext())
{
context.Add(dept);
context.SaveChanges();
}
Note that here you don’t have to explicitly set the EntityState to Added, as this is done by EF Core by it’s own.
The SaveChanges() method which I used earlier is a synchronous method. You can instead use the SaveChangesAsync() method which is an asynchronous method. Asynchronous methods make use of threading and enables server resources to be used more efficiently. So your codes handles more traffic without delays.
The below code does the record creation in the database in Asynchronous way.
var dept = new Department()
{
Name = "Designing"
};
using (var context = new CompanyContext())
{
context.Add(dept);
await context.SaveChangesAsync();
}
The DbContext.AddRange() method is used to insert multiple records at the same time.
Here I am inserting 3 department records.
var dept1 = new Department() { Name = "Development" };
var dept2 = new Department() { Name = "HR" };
var dept3 = new Department() { Name = "Marketing" };
using (var context = new CompanyContext())
{
context.AddRange(dept1, dept2, dept3);
await context.SaveChangesAsync();
}
You can do the same thing from the below code:
var dept1 = new Department() { Name = "Development" };
var dept2 = new Department() { Name = "HR" };
var dept3 = new Department() { Name = "Marketing" };
var deps = new List<Department>() { dept1, dept2, dept3 };
using (var context = new CompanyContext())
{
context.AddRange(deps);
await context.SaveChangesAsync();
}
The Department & Employee tables have many-to-one relationship between them. Here I will insert one new record on each of these 2 tables (Department & Employee).
var dept = new Department()
{
Name = "Admin"
};
var emp = new Employee()
{
Name = "Matt",
Designation = "Head",
Department = dept
};
using (var context = new CompanyContext())
{
context.Add(emp);
await context.SaveChangesAsync();
}
Check I have set the ‘Department’ property of the Employee object to the Department object.
In this way Entity Framework Core will know that the entities are related hence it will insert both of them to their respected tables.
If you check the database you will find both the new records on their respected tables.
Download the source codes: