Posted on 12/29/2020 11:35:55 AM by Admin

What is Entity Framework

Difference between SQL developer and C# developer
C# developer VS SQL developer

In the above figure , I have tried to explain the differences between the thinking process of a C# programmer and a SQL developer.

A SQL developer always thinks in terms of
    • Tables
    • Rows
    • Columns and
    • SQL queries

Whereas a C# programmer thinks in terms of
    • Classes
    • Objects
    • Collections and
    • Methods

It seems very unfair when a C# programmer has to create tables and write SQL queries, cause the C# developer always sees everything as an object, in fact, call ourselves an OOP developer. We think in terms of objects, isn't it?

When we need to access a database in our application, we need to create a persistence Framework. We can create a persistence Framework all by ourselves using plain Ado.Net classes like
    • SqlConnection
    • SqlCommand and
    • SqlDataReader

But writing a persistence framework from scratch is very costly , we have to create
    • A lot of Store procedures
    • Multiple Ado.Net class's objects and
    • Manually map the database objects and records with domain objects.

This is where Entity Framework shines, it frees us from all of the above dirty works and enables us to get things done easily and quickly.

we no longer need to
    • write Store procedures most of the time.
    • Manage Database connections and
    • Manually map database tables and records to our domain objects.

EF does all this work for us. Meaning, Entity Framework is Just awesome.

So, what is an Entity Framework?

EF is an ORM , meaning it is an object-relational mapping tool. If you look at the name (ORM), it basically translates into: mapping objects to relational tables. Basically, the ORM framework/software generates objects (as in OOP) that virtually map the tables in a database. Then you as a programmer would use these objects to interact with the database. So the main idea is to try and shield the programmer from having to write optimized SQL code – the ORM generated objects take care of that for you.

So let’s take a look at a simple example:

Say for instance you had a database with two tables:
    • Employee and
    • Department

With a little bit of configuration on your part, the ORM framework would then create corresponding objects (say, Employees and Departments) that would handle all the database interaction. So let’s say you need to add a new Employee to the database, you would just have to use the ORM’s Employees object to add the new Employee.


   Employees emps=new Employees(); //DbSet
   Employee emp=new Employee(); // single employee object
   emp.Name="Sachin";
   emp.Salary=70000;
   emps.Add(emp);
   emp.SaveChanges(); // this will commit the changes to database.

Entity Framework
Entity Framework

As you can see in the above figure ,the EF converts the following to following
  1. Database to a DbContext Class, in our case a DbOrganizationContext.
  2. Tables to DBSet Class, in our case DbSet ie Employees.
  3. Table rows to DbSet object, in our case each Employee object will represent a row of Employee table.
  4. Table columns to properties of DbSet Class ,In our case Employee Class properties like Id, Name etc.

Entity Framework Mapping
Entity Framework Mapping

DbContext Class

DbContext is an important class in Entity Framework. It is a bridge between your domain or entity classes and the database. In reality A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. we will discuss it in detail in later articles.

DbContext
DbContext

For now think DbContext Class as a primary class that is responsible for interacting with the database. It is responsible for the following activities:
  • Querying: Converts LINQ-to-Entities queries to SQL query and sends them to the database.
  • Change Tracking: Keeps track of changes that occurred on the entities after querying from the database.
  • Persisting Data: Performs the Insert, Update and Delete operations to the database, based on entity states (Modified, Deleted or Inserted)
  • Caching: Provides first-level caching by default. It stores the entities which have been retrieved during the lifetime of a context class.
  • Manage Relationship: Manages relationships using CSDL, MSL and SSDL in Db-First or Model-First approach, and using fluent API configurations in Code-First approach.
  • Object Materialization: Converts raw data from the database into entity objects.

Important Methods of DbContext Class

Method Description
Entry(Object)

Gets a DbEntityEntry object for the given entity providing access to information about the entity and the ability to perform actions on the entity.

Entry<TEntity>(TEntity)

Gets a elative-path">DbEntityEntry<TEntity> object for the given entity providing access to information about the entity and the ability to perform actions on the entity.

OnModelCreating(DbModelBuilder)

This method is called when the model for a derived context has been initialized, but
before the model has been locked down and used to initialize the context. The default
implementation of this method does nothing, but it can be overridden in a derived class
such that the model can be further configured before it is locked down.

SaveChanges()

Saves all changes made in this context to the underlying database.

DbSet Class

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext.Set method.

Method Description
Add(TEntity)

Adds the given entity to the context underlying the set in the Added state such that it will
be inserted into the database when SaveChanges is called.

AddRange(IEnumerable<TEntity>)

Adds the given collection of entities into context underlying the set with each entity being put into
the Added state such that it will be inserted into the database when SaveChanges is called.

Attach(TEntity)

Attaches the given entity to the context underlying the set. That is, the entity is placed
into the context in the Unchanged state, just as if it had been read from the database.

Include(String)

Specifies the related objects to include in the query results.

Remove(TEntity)

Marks the given entity as Deleted such that it will be deleted from the database when SaveChanges is called.
Note that the entity must exist in the context in some other state before this method is called.

SqlQuery(String, Object[])

Creates a raw SQL query that will return entities in this set.
By default, the entities returned are tracked by the context; this can be changed by calling AsNoTracking on the DbSqlQuery<TEntity>returned.
Note that the entities returned are always of the type for this set and never of a derived type.
If the table or tables queried may contain data for other entity types,
then the SQL query must be written appropriately to ensure that only entities of the correct type is returned.

How to work with Entity Framework

You don't have to worry about how DbContext class keep track of changes that we do in DbSet Objects and how does it fire corresponding T-SQL against database .Your OOPs concept are enough to get started with Entity Framework. Just think in terms of Collection and Object.

Suppose there is a List of Employee as shown in below code.


    List emps = new List()
    {
     new Employee(){Id=1,Name="Sachin",Salary=78000},
     new Employee(){Id=2,Name="Arjun",Salary=9000}
    };

If You are asked to add a new Employee object to this collection , then how will you proceed, you will use the Add method isn't it?


Employee emp = new Employee() { Id = 3, Name = "Vikash", Salary = 70000 };
emps.Add(emp);

similarly to remove an object you simply use Remove() method


   emps.Remove(2);

You need to apply the same concepts while using EF in your application, DbSet are the collection of your domain objects as well as public properties of DbContext Class.

So if you have to Add a new row to Employee table then You just need three steps.

Step 1. Create the object of DbContext Class , so that you can access DbSet call it Employees , as all DbSet are properties of DbContext Class.

Step 2. Add new Employee object to the DbSet .

Step 3. Call SaveChanges() method of DbContext class to commit changes to Database.


   OrganizationDbContext db=new OrganizationDbContext(); // create object of DbContext.
   Employee emp = new Employee() { Id = 3, Name = "Vikash", Salary = 70000 };
   db.Employees.Add(emp); // access DbSet (Employees) from DbContext (db) and use Add() method
   db.SaveChanges(); // commit changes to database.

Note:- Each instance of DbContext Class represents a session with the database so always wrap it inside using statement or use a single instance of DbContext throughout the application.