August, 2008

  • Wriju's BLOG

    ADO.NET Entity: Insert Update and Delete

    • 29 Comments

    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!!!

Page 1 of 1 (1 items)