Problem
In Entity Framework, I have a SQL Server table named employ with a single key field entitled ID.
How can I use Entity Framework to delete a single record from a table?
Asked by user2497476
Solution #1
You don’t have to query the object first; you can just use its id to attach it to the context. As an example:
var employer = new Employ { Id = 1 };
ctx.Employ.Attach(employer);
ctx.Employ.Remove(employer);
ctx.SaveChanges();
You can also set the connected entry’s status to deleted:
var employer = new Employ { Id = 1 };
ctx.Entry(employer).State = EntityState.Deleted;
ctx.SaveChanges();
Answered by mt_serg
Solution #2
You can use SingleOrDefault to acquire a single item that matches your criteria and then feed it to your EF table’s Remove method.
var itemToRemove = Context.Employ.SingleOrDefault(x => x.id == 1); //returns a single item.
if (itemToRemove != null) {
Context.Employ.Remove(itemToRemove);
Context.SaveChanges();
}
Answered by Mansfield
Solution #3
var stud = (from s1 in entities.Students
where s1.ID== student.ID
select s1).SingleOrDefault();
//Delete it from memory
entities.DeleteObject(stud);
//Save to database
entities.SaveChanges();
Answered by Alex G
Solution #4
Employer employer = context.Employers.First(x => x.EmployerId == 1);
context.Customers.DeleteObject(employer);
context.SaveChanges();
Answered by Sam Leach
Solution #5
I’m using LINQ with entity framework. Following the code was beneficial to me;
1
using (var dbContext = new Chat_ServerEntities())
{
var allRec= dbContext.myEntities;
dbContext.myEntities.RemoveRange(allRec);
dbContext.SaveChanges();
}
2- For a single disc
using (var dbContext = new Chat_ServerEntities())
{
var singleRec = dbContext.ChatUserConnections.FirstOrDefault( x => x.ID ==1);// object your want to delete
dbContext.ChatUserConnections.Remove(singleRec);
dbContext.SaveChanges();
}
Answered by Baqer Naqvi
Post is based on https://stackoverflow.com/questions/17723276/delete-a-single-record-from-entity-framework