Skip to content

Instantly share code, notes, and snippets.

@guneysus
Forked from tombowers/delete-with-select.cs
Created September 8, 2021 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guneysus/8f26de9dc31ec8232563ea8b98ee615d to your computer and use it in GitHub Desktop.
Save guneysus/8f26de9dc31ec8232563ea8b98ee615d to your computer and use it in GitHub Desktop.
Entity Framework - Update without Select
var id = 1;
using (var db = new entityContext())
{
// Select entity
var entity = db.dbset.FirstOrDefault(e => e.ID == id);
if (entity != null)
{
// Remove Entity
db.dbset.Remove(entity);
db.SaveChanges();
}
}
var id = 1;
using (var db = new entityContext())
{
// Create stub entity
var entity = new myEntity { ID = id };
// Attach the entity to the context.
db.dbset.Attach(entity);
// Remove the entity. This marks it for deletion
db.dbset.Remove(entity);
// Save changes. EF will see that the entity state has changed,
// and process it accordingly. In this case performing a delete query.
db.SaveChanges();
}
try
{
using (var db = new dbContext())
{
// Create new stub with correct id and attach to context.
var entity = new myEntity { PageID = pageid };
db.Pages.Attach(entity);
// Now the entity is being tracked by EF, update required properties.
entity.Title = "new title";
entity.Url = "new-url";
// EF knows only to update the propeties specified above.
db.SaveChanges();
}
}
catch (DataException)
{
// process exception
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment