Introduction

In the previous articles, I've shown how to create a CodeFirst Entity Framework project using Visual Studio and C# .NET. I've looked at how to insert and then amend a record, this time, I'm looking at how to delete a record using CodeFirst technique. Hopefully you still have the project from the previous articles still. If you don't, go through the previous articles to familiarise yourself.

In essence, all you need to do to delete a record is to set the ID and then set the state then save the changes. Lets assume you have eight records and you want to delete the record with the ID of 4. You can either.

For our example, we are going to use the latter to delete the record. Once the record has been set, we simply set the status of the record and call SaveChanges as shown in the example below.

    static void Main(string[] args)
        {
            string sConn = "Data Source=<Your Server>;Initial Catalog=Shop;Integrated Security=True";

            using (var ctx = new Shop(sConn))
            {
                Customer oCust = new Customer();
                oCust.CustomerID = 4;
                ctx.Entry(oCust).State = System.Data.Entity.EntityState.Deleted;
                ctx.SaveChanges();
            }
        }
If the ID doesn't exist then the record will not be deleted, an error will be thrown and your application will need to handle it.

Tags - Entity Framework

Last Modified : June 2023


About... / Contact.. / Cookie...