Insert Records in Entity Framework Core

Insert Records in Entity Framework Core

CRUD Operations can be easily performed by Entity Framework Core. EF Core executes Insert Operation for the entities whose EntityState is Added when the DbContex.SaveChanges() method is called.

EntityState is an enumeration that stores the state of the entity. It can have one out of the 5 different values, these are ‘Added’, ‘Deleted’, ‘Detached’, ‘Modified’ & ‘Unchanged’. If you want to add a new entity(record) then its EntityState should be ‘Added’, if you want to update an entity then it must be ‘Modified’, for deleting an entity it should be ‘Deleted’ and so on.
Application Setup

I will be dealing with the same database that contains 2 tables – Employee & Department. A department can have more than one employee so there is many-to-one relationship between them.

I have 2 entity classes, which are Department.cs & Employee.cs, kept inside the Models folder.

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 class Department
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Employee> Employee { get; set; }
}

I also have a Context class named CompanyContext.cs on my Models folder.

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");
        });
    }
}

Inserting a Single Record on the Database

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.

inserting record on 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.Department.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 its own.

Inserting Multiple Records on the Database

The DbContext.AddRange() method is used to insert multiple entities 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.Department.AddRange(dept1, dept2, dept3);
    context.SaveChanges();
}

inserting mulitple records

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.Department.AddRange(deps);
    context.SaveChanges();
}

Inserting Related Records on the Database

The Department & Employee tables have many-to-one relationship. 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.Employee.Add(emp);
    context.SaveChanges();
}

Check I have set the Department property of the Employee object to the Department object.
In this way EF Core will know 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.

insert related records

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.