Practical Introduction To Entity Framework: Day 1

What is Entity Framework?

It is an Object Relational Mapper (ORM) that enables programmers to communicate with a relational database.

What is ORM?

Object Relational Mapper: processing a relational database and mapped in such way so as programmers can use it in their code easily.

Why Entity Framework?

Using this we can do all the DB select, insert, update, delete operations without writing ADO .Net code that we write for every single query of a database.

  1. To do the faster development use Entity Framework
  2. Connect with any database like SQL or Oracle
  3. Auto-generated Model
  4. Works well with Stored Procedures

First create a table in your database: I have attached my DB structure here.

Entity Framework

Now in Visual Studio add a new item: ADO entity Model.

ADO entity Model

ADO entity Model1

Select your database and save the entity to do CRUD operations.

CRUD operations

Select your tables.

CRUD operations1

After clicking on Finish an edmx is created for your project.

Now

Create Entity Object to do CRUD operations

  1. FirstDayEntities ObjEntity = new FirstDayEntities();   
  2.  
  3.         #region Read All Merchants          
  4.         var ObjMerchantsList = ObjEntity.Merchants;    
  5.         #endregion  
  6.  
  7.         #region Insert   
  8.         Merchant ObjMerchant = new Merchant() { Name = "Mangesh Gaherwar", Address = "Solapur" };          
  9.         ObjEntity.AddToMerchants(ObjMerchant); //   ObjEntity.Merchants.AddObject(ObjMerchant); //both r same        
  10.         int InsertResult = ObjEntity.SaveChanges();  
  11.         #endregion  

  12.         #region Update  
  13.         Merchant ObjUpdateMerchant = ObjEntity.Merchants.Where<Merchant>(a => a.Name == "Mangesh Gaherwar").FirstOrDefault();  
  14.         ObjUpdateMerchant.Address = "Kamote";  
  15.         int UpdateResult = ObjEntity.SaveChanges();  
  16.         #endregion  
  17.  
  18.         #region Delete  
  19.         Merchant ObjDeleteMerchant = ObjEntity.Merchants.Where<Merchant>(a => a.Name == "Mangesh Gaherwar").FirstOrDefault();  
  20.         ObjEntity.Merchants.DeleteObject(ObjDeleteMerchant);    
  21.         int DeleteResult = ObjEntity.SaveChanges();  
  22.         #endregion 

That's it.

If your database table structure is the same then only change the connection string in the web.config

We will see some more fundamentals in Practical of Entity Framework: Day 2.

Please find the attached source code Zip.

Thank you for reading.