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

Create, Read, Update, Delete using entity framework

Entity Framework CRUD Operations in C#

In this tutorial we will learn all CRUD Operations in Entity Framework, How to create or add, select or read, update or edit and delete data using entity framework in C#

But before you start with this exercise, you should be familiar with DBContext object (ex: Entities context = new Entities()).

Create or Add data example
public tbStudent AddStudent(tbStudent student)            
{
    tbStudent _student = null;

    using (Entities context = new Entities())
    {
        _student = context.tbStudents.Add(student);
        context.SaveChanges();
    }

    return _student;
}

Read or Select data example

public List<tbStudent> getAllStudents()
{
    List<tbStudent> _students = null;

    using (Entities context = new Entities())
    {
        _students = context.tbStudents
        .ToList<tbStudent>();
    }

    return _students;
}

Read or Select data with Where clause example

public tbStudent getStudent(int id)
{
tbStudent _student = null;
using (Entities context = new Entities())
{
_student = context.tbStudents
.Where(s => s.studentId == id)
        .FirstOrDefault<tbStudent>();
    }

    return _student;
}

Update or Edit data in Entity Framework

public bool updateStudent(tbStudent student) {
tbStudent _student = null;
bool _isDone = false;
using (Entities context = new Entities())
{
_student = context.tbStudents
.Where(s => s.studentId == student.studentId)
        .FirstOrDefault<tbStudent>();
            
        if (_student != null)
        {
            // updating new values
            _student.FullName = student.FullName;
            _student.email = student.email;
            
            context.Entry<tbStudent>(_student).State = EntityState.Modified;
            context.SaveChanges();
            _isDone = true;
        }
    }
            
    return _isDone;
}

Delete Example Entity Framework

Delete Data with Where clause using Entity Framework Example

public bool deleteStudent(int id) {
tbStudent _student = null;
bool _isDeleted = false;
using (Entities context = new Entities())
{
_student = context.tbStudents
.Where(s => s.studentId == id)
        .FirstOrDefault<tbStudent>();
            
        if (_student != null)
        {
        context.Entry<tbStudent>(_student).State = EntityState.Deleted;
        context.SaveChanges();
        _isDeleted = true;
        }
    }
return _isDeleted;
}

Above CRUD operation code is tested working properly, can be implemented in your project, only change the object name


Comment
Name
Email
Website
Subscribe
 
CRUD Operation using Entity Framework