Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Learn CRUD operations using entity framework

Entity Framework Example C#

In this article we will learn all CRUD Operations in Entity Framework, How to create or add, select or read, update or edit and delete data.
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 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;
}

Comment
Name Email Website
Subscribe
 
CRUD Operation using Entity Framework

Group Training