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

CRUD operation using EntityFramework Core

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

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

// 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

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

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


In all above examples we assumed you already familiar with DbContext class and how to set up connection string in .Net Core

Comment
Name Email Website
Subscribe
 
CRUD operation using EF Core

Group Training