-
-
Save jaysudodeveloper/ba1d55ffc8d95fc3549f8aeef3480142 to your computer and use it in GitHub Desktop.
Entity Framework - Update without Select
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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