Delete a single record from Entity Framework?
It's not necessary to query the object first, you can attach it to the context by its id.
Like this:
var employer = new Employ { Id = 1 };
ctx.Employ.Attach(employer);
ctx.Employ.Remove(employer);
ctx.SaveChanges();
Alternatively, you can set the attached entry's state to deleted :
var employer = new Employ { Id = 1 };
ctx.Entry(employer).State = EntityState.Deleted;
ctx.SaveChanges();
How do i delete single record from table using EF 6.1.1
There are no changes about how to delete an entity between EF 4 and EF 6. To delete an entity using Entity Framework, you need to use the Remove
method on DbSet
. Remove
works for both existing and newly added entities.
Calling
Remove
on an entity that has been added but not yet saved
to the database will cancel the addition of the entity. The entity is
removed from the change tracker and is no longer tracked by theDbContext
.Calling
Remove
on an existing entity that is being change-tracked
will register the entity for deletion the next timeSaveChanges
is
called.
Deleting with loading from the database
As the example you show in your question, you need to load first the existing entity from your context to delete it. If you don't know the Id
, you can execute a query as I show below to find it first:
var report= (from d in context.StudentReportDetail
where d.ReportName == "Report"
select d).Single();
context.StudentReportDetail.Remove(report);
context.SaveChanges();
Deleting without loading from the database
If you need to delete an entity, but it’s not already in memory, it’s a little inefficient to retrieve that entity from the database just to delete it. If you know the key of the entity you want to delete, you can attach a stub that represents the entity to be deleted, and then delete this stub. A stub is an instance of an entity that just has the key value assigned. The key value is all that’s required for deleting entities.
var toDelete = new StudentReportDetail {Id = 2 };
context.StudentReportDetail.Attach(toDelete);
context.StudentReportDetail.Remove(toDelete);
context.SaveChanges();
Other way could be changing the entity's state to Deleted
.DbContext
has methods called Entry
and Entry<TEntity>
, these methods get a DbEntityEntry
for the given entity and provide access to the information about the entity and return a DbEntityEntry
object able to perform the action on the entity. Now you can perform the delete operation on the context by just changing the entity state to EntityState.Deleted
:
var toDelete = new StudentReportDetail {Id = 2 };
context.Entry(toDelete).State = EntityState.Deleted;
context.SaveChanges();
Using a 3rd party library
There is another way but is using a 3rd party library, EntityFramework Plus, there is a nugget package you can install. You can use the batch delete operation:
context.StudentReportDetail
.Where(u => u.Id== stuDetails)
.Delete();
How do I delete multiple rows in Entity Framework (without foreach)
If you don't want to execute SQL directly calling DeleteObject in a loop is the best you can do today.
However you can execute SQL and still make it completely general purpose via an extension method, using the approach I describe here.
Although that answer was for 3.5. For 4.0 I would probably use the new ExecuteStoreCommand API under the hood, instead of dropping down to the StoreConnection.
Delete record using entity framework
You need to call SaveChanges
method of DbContext
after you made the changes. Otherwise changes will not be committed to databse.
Delete all rows from a table with an Entity Framework function using C#
Raw SQL is the preferred method to perform bulk changes like this. But the best way to do it otherwise is to fetch all the IDs and construct "Stub Entity" instances with only the IDs populated.
EG
var toDelete = db.Alerts.Select(a => new Alert { Id = a.Id }).ToList();
db.Alerts.RemoveRange(toDelete);
db.SaveChanges();
Unable to delete record from database Entity Framework C#
If you want to delete a User
, you would have to delete all Log
entries associated with that user first.
var apiKey = String.Empty; // The id of the user you want to delete
using (var context = new UserContext())
{
User userToDelete = checkIfUserExistsWithApiKeyandReturnUser(apiKey);
if (userToDelete != null)
{
var userLogs = context.Logs.Where(l => l.userAPIKey == apiKey);
if (userLogs.Any())
{
context.Logs.RemoveRange(userLogs);
}
context.Users.Attach(userToDelete);
context.Users.Remove(userToDelete);
context.SaveChanges();
}
}
Entity Framework: delete record with its sub-records
That the table is self referencing is application logic, it is not expressed in the SQL definition, and therefore is not understood by EF.
To delete these records through EF you need to write a routine that starts at the top and loads all the sub items. Then mark all these items as deleted, then call save changes.
To delete an item:
context.DeleteObject(item);
context.SaveChanges();
How do I delete a set of records in Entity Framework .Core?
Since you have already gotten the list of associated notes, then use RemoveRange
on the DbSet
, removing each element. Save changes can be applied after.
//...
var HCF = await _context.HCF.FindAsync(id);
_context.HCF.Remove(HCF);
IQueryable<HCReportingNote> notesQuery =
from n in _context.HCReportingNotes
where n.HCFId == HCF.ID
select n;
_context.HCReportingNotes.RemoveRange(notesQuery);
await _context.SaveChangesAsync();
//...
Related Topics
Case Insensitive Regex Without Using Regexoptions Enumeration
Mvvm Show New Window from Vm When Seperated Projects
Copying Free Hand Drawing from Panel in Visual Studio 2013
How to Add Custom Http Header for C# Web Service Client Consuming Axis 1.4 Web Service
How to Get the Last Four Characters from a String in C#
How to Copy File - Access to the Path Is Denied
How to Simulate a Mouse Click at a Certain Position on the Screen
Differencebetween Xamarin.Form's Layoutoptions, Especially Fill and Expand
How to Change Route to Username After Logged In
Correct Implementation of a Custom Config Section with Nested Collections
JSON Serializer Object with Internal Properties
How to Create "Embedded" SQL 2008 Database File If It Doesn't Exist
Factory Pattern in C#: How to Ensure an Object Instance Can Only Be Created by a Factory Class
How to Maximize the Browser Window in Selenium Webdriver (Selenium 2) Using C#
Resize Wpf Window and Contents Depening on Screen Resolution