How to delete a record using .NET CodeFirst Entity Framework
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.
- Fetch the record to delete using Find for example.
- Create an empty record with the ID of the record to delete.
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.
Other Articles of Interest
Next Article : How to use Database Transactions with .NET CodeFirst Entity Framework
Previous Article : How to amend a record using CodeFirst Entity Framework .NET
Tags - Entity Framework
Last Modified : 29th May 2023
Date Published : 14th August 2022
Comments and Questions
There's no register feature and no need to give an email address if you don't want to. All messages will be reviewed before being displayed. Comments may be merged or altered slightly, such as if it contains an email or website address.
You can decline to give a name; if that is the case, the comment will be attributed to a random star. A name is preferred, even if it's a random made-up one by yourself.
If you give an email address, you may receive an email notifying you when someone else has added a comment to the same page. In the email will be a link to unsubscribe to further notifications.