Free Web Development Online Tutorials, Learn to Code
CRUD Operations in Entity Framework Core, Learn Entity Framework Core with C#, Code First, DB First Approach

EntityFramework Core CRUD Examples

In this tutorial we will explain you how to Create, Read, Update and Delete data using Entity Framework Core.

These entire examples can work with Asp.Net Core or any other type of application written using .Net Core C#.

Create or Add data using EF Core

Code for adding data to database using entity framework core

public Student AddStudent(Student s)
{
    using (EFContext context = new EFContext())
    {
        context.tbStudent.Add(s);
        context.SaveChanges();
    }
    return s;
}

Read or Select data using EF Core

Code for selcting or reading data from database using entity framework core

// example of reading a list of data
public List<Student> GetAllStudents()
{
List<Student> list = new List<Student>();
var context = new EFContext();
list = context.tbStudent
.ToList<Student>(); return list;
}
// example of reading a single row public Student GetStudent(int sid)
{
Student _s=null;
using (EFContext context = new EFContext())
{
_s = context.tbStudent
.Where(s => s.StuId == sid)
        .FirstOrDefault<Student>();
               
    }
    return _s;
}
Update data using EF Core

Code for updating data to database using entity framework core

public Student UpdateStudent(Student student)
{
Student _s = null;
using (EFContext context = new EFContext())
{
_s = context.tbStudent
.Where(s => s.StuId == student.StuId)
                .FirstOrDefault<Student>();
        if (_s != null)
        {
            _s.Firstname = student.Firstname;
            _s.Lastname = student.Lastname;
            _s.Email = student.Email;
            _s.ContactNumber = student.ContactNumber;
            context.SaveChanges();
        }
    }
    return _s;
}
Delete data using EF Core

Code for deleting data from database using entity framework core

public bool DeleteStudent(int stuid)
{
bool _isDeleted = false;
Student _s = null;
var context = new EFContext();
_s = context.tbStudent
.Where(s=>s.StuId==stuid)
    .FirstOrDefault<Student>();
        if (_s != null)
        {
        context.tbStudent.Remove(_s);
        context.SaveChanges();
        _isDeleted = true;
        }
    return _isDeleted;
}

Assumption: we assumed you already familiar with DbContext class and how to set up connection string in .Net Core

Comment
Name
Email
Website
Subscribe