Types of Entities in Entity Framework
There are two types of Entities in entity framework: POCO Entities and Dynamic Proxy.
POCO Entities (Plain Old CLR Object)
A POCO entity is a class that does not depend on any framework-specific base class. It is like any other normal .NET CLR class; that is why it is called "Plain Old CLR Objects". POCO entities are supported in both EF6 and EF Core.
These POCO entities (also known as Persistent-ignorant Objects) support most of the same queries insert, update, and delete behaviors as Entity types that are generated by the Entity Data Model.
Here is the example of the Student POCO entity.
Dynamic Proxy Entities (POCO Proxy)
Dynamic Proxy is a runtime proxy class which wraps the POCO entity. Dynamic Proxy entities allow lazy loading.
POCO entity should meet the following requirements to become a POCO proxy.
Here is the following POCO entity that meets all of the above requirements to become a dynamic proxy entity at runtime.
At runtime, Entity Framework API will create an instance of a dynamic proxy for the above Student Entity. The type of dynamic proxy for Students will be System.Data.Entity.DynamicProxies.Student, as shown below:
We use ObjectContext.GetObjectType() to find the wrapped type by the dynamic proxy as shown below:
EntityState in EntityFramework
Entity Framework API maintains the state of each entity during its lifetime. Each entity has a state, which is based on the operation performed on it by the context class. The state of the entity represented by an enum System.Data.Entity.EntityState in EF6 and Microsoft.EntityFrameworkCore.EntityState in EF core with the following values:
The context not only holds the reference of all the objects when we retrieved from the database but it also keeps track of the states of the entity and maintains the modification which is made to the properties of the entity. This feature is known as Change Tracking.
The change in the state of the entity from unchanged to the modified state is the only state which automatically handled by the context. All the other changes must be made explicitly using the proper methods of DbContext or DbSet.
Entity Framework API builds and executes the INSERT, UPDATE, and DELETE command, which is based on the state of the entity when the context.SaveChanges() method is called. It executes the INSERT command for the entities to add the state, UPDATE command is used for the entities to modify the state, and the DELETE command is used for the entities to delete the state. The context does not track the entities in the Detached state.