DbEntityEntry Class in EntityFramework

The DbEntityEntry is an important class, useful in retrieving various information about an entity. You can get an instance of DBEntityEntry of a particular entity by using the Entry method of DbContext. For example:

DbEntityEntry studentEntry = dbcontext.Entry(entity);

The DbEntityEntry enables you to access the entity state, and current and original values of all properties of a given entity. The following example code shows how to retrieve important information of a particular entity.

using (var dbCtx = new SchoolDBEntities())
{
    //get student whose StudentId is 1
    var student = dbCtx.Students.Find(1);

    //edit student name
    student.StudentName = "Edited name";

    //get DbEntityEntry object for student entity object
    var entry = dbCtx.Entry(student);

    //get entity information e.g. full name
    Console.WriteLine("Entity Name: {0}", entry.Entity.GetType().FullName);

    //get current EntityState
    Console.WriteLine("Entity State: {0}", entry.State );

    Console.WriteLine("********Property Values********");

    foreach (var propertyName in entry.CurrentValues.PropertyNames )
    {
        Console.WriteLine("Property Name: {0}", propertyName);

        //get original value
        var orgVal = entry.OriginalValues[propertyName];
        Console.WriteLine("     Original Value: {0}", orgVal);
                    
        //get current values
        var curVal = entry.CurrentValues[propertyName];
        Console.WriteLine("     Current Value: {0}", curVal);
    }

}
    
Output:
Entity Name: Student
Entity State: Modified
********Property Values********
Property Name: StudentID
Original Value: 1
Current Value: 1
Property Name: StudentName
Original Value: First Student Name
Current Value: Edited name
Property Name: StandardId
Original Value:
Current Value:

The DbEntityEntry enables you to set an EntityState as shown below.

context.Entry(student).State = System.Data.Entity.EntityState.Modified;

Visit MSDN for more information on DbEntityEntry class.