ADO.NET Entity: Insert Update and Delete

ADO.NET Entity: Insert Update and Delete

Rate This
  • Comments 28

For small blogs, it requires more references and explanation, which sometimes are redundant. So I thought of writing single blog which is combination of topics more or less related to one thing.

 

I am exploring ADO.NET Entity Framework and have been trying things out there. Here I am planning to demonstrate how to do insert, update and delete.

 

Here I will use a database created by me. In the Emp table there are two columns Id (Primary and auto-generated) and Name (simple varchar(50)).

image

Now I will create TestDB.edmx out of this database.

image

Insert

 

using (TestDBEntities ctx = new TestDBEntities())

{

    //Create new Emp object

    Emp e = new Emp() { Name = "Test Employee" };

 

    //Add to memory

    ctx.AddToEmp(e);

 

    //Save to database

    ctx.SaveChanges();

}

 

 

Update

 

using (TestDBEntities ctx = new TestDBEntities())

{

    //Get the specific employee from Database

    Emp e = (from e1 in ctx.Emp

             where e1.Name == "Test Employee"

             select e1).First();

 

    //Change the Employee Name in memory

    e.Name = "Changed Name";

 

    //Save to database

    ctx.SaveChanges();

}

 

Delete

 

using (TestDBEntities ctx = new TestDBEntities())

{

    //Get the specific employee from Database

    Emp e = (from e1 in ctx.Emp

             where e1.Name == "Test Employee"

             select e1).First();

 

    //Delete it from memory

    ctx.DeleteObject(e);

 

    //Save to database

    ctx.SaveChanges();

}

 

In my next post I will write about “how to handle CRUD with Relationship”.

Namoskar!!!

Leave a Comment
  • Please add 7 and 8 and type the answer here:
  • Post
  • Hi Wriju,

            Can I update multiple employees through your update query ?

  • this example is easy to understand. thanks

  • good work

  • Great to the point examples. Thank you.

  • DeleteObject does not work in EF5

  • Just wanted to say how great I thought your tutorial was. Its really helped me a lot. Thank you for writing it

  • There is no such method as ctx.AddToEmp()

  • It gets created based on the Entity so if you have an Entity "Dept" there will be a method AddToDept

  • Thanks a lot. This article has helped me really well.

  • hw can i upadate no of records at one time.....

  • Its very simple and very clear....Thanks for this post...

  • I m using VS-2012 when  i m using context. i m not get the deleteobject() method

  • Thank you man!

    Simple and excelent samples!

Page 2 of 2 (28 items) 12