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 processes a relational database and mapping in such a way that programmers can use it in their code easily.
Why Entity Framework?
Using this we can do all the DB select, insert, update, and delete operations without writing ADO .Net code that we write for every single query of a database.
- To do faster development use Entity Framework
- Connect with any database like SQL or Oracle
- Auto-generated Model
- Works well with Stored Procedures
First, create a table in your database I have attached my DB structure here.
Now in Visual Studio add a new item ADO Entity Model.
Select your database and save the entity to do CRUD operations.
Select your tables.
After clicking on Finish an edmx is created for your project.
Now
Create Entity Object to do CRUD operations
FirstDayEntities ObjEntity = new FirstDayEntities();
#region Read All Merchants
var ObjMerchantsList = ObjEntity.Merchants;
#endregion
#region Insert
Merchant ObjMerchant = new Merchant() { Name = "Mangesh Gaherwar", Address = "Solapur" };
ObjEntity.AddToMerchants(ObjMerchant); // ObjEntity.Merchants.AddObject(ObjMerchant); //both r same
int InsertResult = ObjEntity.SaveChanges();
#endregion
#region Update
Merchant ObjUpdateMerchant = ObjEntity.Merchants.Where<Merchant>(a => a.Name == "Mangesh Gaherwar").FirstOrDefault();
ObjUpdateMerchant.Address = "Kamote";
int UpdateResult = ObjEntity.SaveChanges();
#endregion
#region Delete
Merchant ObjDeleteMerchant = ObjEntity.Merchants.Where<Merchant>(a => a.Name == "Mangesh Gaherwar").FirstOrDefault();
ObjEntity.Merchants.DeleteObject(ObjDeleteMerchant);
int DeleteResult = ObjEntity.SaveChanges();
#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.
Go to part 2