Getting started with Entity Framework Core

Recently, Microsoft has launched .NET core. They had to rewrite the whole code from scratch to make it more modular and reusable. Also, they completely rewrite the Entity Framework and the good part is that they made it very light weighted but some of their concepts differ from old EF, one of such feature is when we try to update an entity in old entity framework then we need to write three lines:

public int Update<T>(T entity) where T : class
{
    var entry = DataContext.Entry(entity);
    DbSet<T>().Attach(entity);
    entry.State = EntityState.Modified;
    return DataContext.SaveChanges();
}

But it is changed in EF Core to make it easy for developers and of course, this process is cumbersome.

I am assuming that you have the basic knowledge of .NET Core to make the perform Add, Edit, Display and Delete feature in the User Interface. So, I am skipping this part and it is also not the purpose of this blog.

Before starting with CRUD operations we need to setup Entity Framework in a project. Let’s start with it:

  1. Create a project using .NET core: For this, Open Visual Studio (VS) and navigate to File > New > Project. Select Template > Visual C# > .NET Core > ASP.NET Core Web Application (.NET Core).
  2. When you click OK, VS asks you to select a template. Select Web Application and choose latest ASP.NET Core version.
  3. We need to install Entity Framework. For this, you need to install following three packages either from Package Manager Console or from Nuget UI:
    1. EntityFrameworkCore
    2. EntityFrameworkCore.Relational
    3. EntityFrameworkCore.SqlServer

Now our project is ready and we need to setup infrastructure for Entity Framework. For this we need our DataContext class who will be responsible for all database related operations. It would look something like this:

public class DataContext : DbContext
{
        public DataContext(DbContextOptions<DataContext> options) : base(options)
        {

        }

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

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employee>().ToTable("Employees");
        }
}

I am doing CRUD operations for an Employee only. So, I mentioned the DbSet for Employees table only. If you are working with multiple tables then you need to specify each table there.

In OnModelCreating(ModelBuilder modelBuilder) method we map the table and columns of our database table to POCO class (Employee). If you are having the column names same as your POCO’s property name then you don’t need to specify it explicitly.

The next thing is to register our DataContext class object in a HttpPipeline to avoid creating its object every time and get it from there. For this you need to make an entry in ConfigureServices method of Starup class with this code:

services.AddDbContext<DataContext>(options =>  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

Here DefaultConnection is the name of the Connection String that contains the database credential of our databse and it is stored in appsettings.json file:

"ConnectionStrings": {
    "DefaultConnection": "Server=PRATEEK\\SQLSERVER2014DEV;Database=EntityFrameworkDemo;Trusted_Connection=True;MultipleActiveResultSets=true"
}

 

Now, our project is ready to do CRUD operations.

 I am considering following Employee class for the operations:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string Address { get; set; }
}

Create Operation: We can do it like this:

[HttpPost]
public async Task<IActionResult> Add(Employee employee)
{
	if(employee != null && ModelState.IsValid)
	{
		await _dataContext.Employees.AddAsync(employee);
		await _dataContext.SaveChangesAsync();
		return RedirectToAction("Index");
	}
	return View(employee);
} 

Read Operation: We can do it like this:

public async Task<IActionResult> Details(int id)
{
	var employee = await _dataContext.Employees.FirstOrDefaultAsync(x => x.Id == id);
	return View(employee);
}

Update Operation: We can do it like this:

[HttpPost]
public async Task<IActionResult> Edit(Employee employee)
{
	if (employee != null && ModelState.IsValid)
	{
		_dataContext.Employees.Update(employee);
		await _dataContext.SaveChangesAsync();
		return RedirectToAction("Index");
	}
	return View(employee);
}

Delete Operation: We can do it like this:

[HttpPost]
public async Task<string> Delete(int id)
{
	var employee = await _dataContext.Employees.FirstOrDefaultAsync(x => x.Id == id);

	if(employee != null)
	{
		_dataContext.Employees.Remove(employee);
		await _dataContext.SaveChangesAsync();
		return "Success";
	}
	
	return "Error";
}