Skip to content

Instantly share code, notes, and snippets.

@jaysudodeveloper
Forked from tombowers/delete-with-select.cs
Created December 7, 2019 08:37
Show Gist options
  • Save jaysudodeveloper/ba1d55ffc8d95fc3549f8aeef3480142 to your computer and use it in GitHub Desktop.
Save jaysudodeveloper/ba1d55ffc8d95fc3549f8aeef3480142 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