I am trying to simply load an entity, modify a property and then save it back to the database.
var db = new NewsletterContext();
var newsletter = db.Newsletters.Find(x => x.ID==newsletterID);
newsletter.SomeProperty = 5;
db.SaveChanges();
This causes a validation error as there are some properties on the newsletter object which are required and apparently not loaded when I do a Find()
.
I can solve this using an Include()
for each required property followed by a Where()
:
var db = new NewsletterContext();
var newsletter = db.Newsletters.Include(x => x.RequiredProp1)
.Include(x => x.RequiredProp2).Include(x => x.RequiredProp3)
.Where(x => x.ID==newsletterID)
.FirstOrDefault();
db.SaveChanges();
This isn't a very elegant solution and will break if I add more required properties to the Newsletter
object.
Is there a better solution?