Entity Framework Core Query to Database.

In this tutorial will discuss to write queries into entity framework core and below point and querying entity framework core.

Entity Framework Core uses Language Integrated Query (LINQ) to query data from the database.

      • LINQ allows you to use C# (or your .NET language of choice) to write strongly typed queries based on your derived context and entity classes.
      • Querying in Entity Framework Core remains the same as in EF 6 to load entities from the database.
      • It provides more optimized SQL queries and the ability to include C#/VB.NET functions into LINQ-to-Entities queries.

Step 1: Create interface ‘IStudentContract.cs’.

public interface IStudentContract
{
   Student GetStudent(int id);
   List GetAllStudent();
   List GetAllStudentByName(string name);
}

Step 2: Create service ‘StudentService.cs’ which impments the above contract.

public class StudentService : IStudentContract
{
   public List GetAllStudent()
   {
     throw new NotImplementedException();
   }

   public List GetAllStudentByName(string name)
   {
     throw new NotImplementedException();
   }

   public Student GetStudent(int id)
   {
    throw new NotImplementedException();
   }
}

Let add functionality into the above service, First we query to database for get all student from database.

public List GetAllStudent()
{
     var context = new SchoolContext();
     List students = context.Student.ToList();
     return students;
}

In Above query we are getting the all records of the student but we require load the student address also but in entity framework core its not by default loading for that we need to make use ‘Include

public List GetAllStudent()
{
   var context = new SchoolContext();
   List students = context.Student.Include(c => c.StudentAddress).ToList();
   return students;
}

Include

The Include method specifies the related objects to include in the query results. It can be used to retrieve some information from the database and also want to include related entities. Now let’s say we have a simple model which contains three entities.

The Include method works quite well for Lists on objects, but what if there is a need for multiple levels of depth. For example, Student contains a list of Address and each address then contains a city details. So in such cases

ThenInclude

EF Core has a new extension method ThenInclude(). You can drill down thru relationships to include multiple levels of related data using the ThenInclude method.

AsNoTracking.

In the Entity Framework-based applications, the DbContext / Object Context is responsible for tracking the changes done in the objects, so the correct update is done to the database when the SaveChanges() method of the context is called. When we retrieve entities using an object query, the Entity Framework puts these entities in a cache and tracks whatever changes are made on these entities until the savechanges method is called.

Sometimes we do not want to track some entities because the data is only used for viewing purposes and other operations such as insert, update, and delete are not done. For example the view data in a read-only grid.

The AsNoTracking() extension method returns a new query and the returned entities will not be cached by the context (DbContext or Object Context). This means that the Entity Framework does not perform any additional processing or storage of the entities that are returned by the query. 

public List GetAllStudent()
{
   var context = new SchoolContext();
   List students = context.Student.Include(c => c.StudentAddress).AsNoTracking().ToList();
   return students;
}

The AsNoTracking method can save both execution times and memory usage. So it improves the application performance Applying this option really becomes important when we retrieve a large amount of data from the database.

Let complete add example of get single object of student by id and name.

public class StudentService : IStudentContract
{

   public List GetAllStudent()
   {
     var context = new SchoolContext();
     List students = context.Student.Include(c => c.StudentAddress).AsNoTracking().ToList();
     return students;
   }

   public List GetAllStudentByName(string name)
   {
     var context = new SchoolContext();
     List students = context.Student.Where(c => c.Name.Equals(name)).ToList();
     return students;
   }

   public Student GetStudent(int id)
   {
     var context = new SchoolContext();
     Student student = context.Student.Where(c => c.ID == id).FirstOrDefault();
     return student;
   }
}

You can watch our video version of this tutorial with step by step explanation.