Monday, 17 October 2016

Perform CRUD operations using Navigation Properties

In this article, we will discuss:

  • Retrieving Specific Item

  • Retrieving List of Items

  • Adding an Item

  • Updating an Item

  • Deleting an Item

using Navigation Properties.

 
We will reuse the entity model that we have created earlier. It is recommended to understand Entity framework Relationships and navigational properties here.
EntityDataModel_Database Approach
 

Retrieving Specific Item


Description:

  • create the DbContext object and using this object, you can fetch the Employer by the given employerId function
  • If we find an Employer object with this ID, we retrieve the Employees associated with it. Internally, Entity Framework is generating a SQL to fetch all the employees associated with this employerid and return all the records as a collection of Employee entities

Retrieving List of Items:


Description:

  • create the DbContext object and using this object, you can fetch the Employer by the given employerId function.
  • If you find an Employer object with this ID, you retrieve the Employees associated with it.Internally, Entity Framework is generating a SQL to fetch all the employees associated with this employerid and return all the records as a collection of Employee entities

Adding an Item


Description:

  • create the DbContext object and using this object, you can fetch Employer by the given employerId.
  • If you find an Employer object with this ID, you add the Employee object to the employer’s Employee collection and finally save the changes to database with db.SaveChanges();.
  • What happens here is that if this Employee entity points to an existing Employee record in the table, the EmployerId value for that employee record will be updated to the ID of the new Employer. If this Employee record does not exist in the database, then a new record for this Employee will be created, and it will have the EmployerId of the given Employer object.

  • Updating an Item:


    Description:

    • Create DbContext Object
    • Fetch the Employer by the given employerId
    • Find the existing Employee by using the ID in the new Employee object
    • If the Employee is found, Update Employee with new values
    • Save the changes. Please note that it is very important to call save changes since otherwise there will be no modifications to the data.

    Deleting an Item


    Description:

    • Create DbContext Object
    • Fetch the Employer by the given employerId
    • Find the existing Employee by using the ID in the new Employee object
    • If the Employee is found, delete Employee
    • Save the changes. Please note that it is very important to call save changes since otherwise there will be no modifications to the data.
    Thanks for visiting !!

    No comments:

    Post a Comment