Retrieving Person Details from Database using Entity Framework in C#

which retrieves a list of person details from the database using Entity Framework in C#

 Introduction:

In this blog article, we will focus on understanding and explaining the GetPerosonDetail method, which retrieves a list of person details from the database using Entity Framework in C#. The method will leverage LINQ to Entities to fetch data and will return a custom model containing both basic information and address details.


Understanding the GetPerosonDetail Method:

Let's break down the code of the GetPerosonDetail method and understand each step:


public List<PersonDetailModal> GetPerosonDetail(): The method signature indicates that this function returns a list of PersonDetailModal objects.


using (var context = new CrudApplicatonEntities()): The code utilizes a using statement to create an instance of the CrudApplicatonEntities database context. This ensures that the context is properly disposed of after its use.


var result = context.PersonDetail.Select(...): The method utilizes LINQ to Entities to query the PersonDetail table from the database.


Select(x => new PersonDetailModal() { ... }): The Select method projects each PersonDetail entity in the database to a new instance of the custom model PersonDetailModal.


Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Email = x.Email: The properties of the PersonDetail entity are mapped to the corresponding properties of the PersonDetailModal object.


Address = new AddressDetailModal() { ... }: The Address property of the PersonDetailModal object is mapped to a new instance of the custom model AddressDetailModal.


Id = x.AddressDetail.Id, Street = x.AddressDetail.Street, City = x.AddressDetail.City, State = x.AddressDetail.State, PostCode = x.AddressDetail.PostCode, Country = x.AddressDetail.Country: The properties of the AddressDetail entity are mapped to the corresponding properties of the AddressDetailModal object.


ToList(): The query is executed using the ToList() method, which returns the result as a list of PersonDetailModal objects.


return result;: The list of PersonDetailModal objects is returned as the output of the method.


Conclusion:

The GetPerosonDetail method retrieves person details from the database using Entity Framework and LINQ to Entities. It returns a list of custom model objects (PersonDetailModal) containing both basic information and address details. This method serves as a foundation for fetching data from the database and can be further expanded or integrated into a broader application for displaying, processing, or manipulating person information.

Comments