I have a view model that encapsulates only some of the database model properties. These properties contained by the view model are the only properties I want to update. I want the other properties to preserve their value.
During my research I found this answer which appears to be perfect for my needs however, despite my best efforts, I cannot get the code to work as expected.
Here is an isolated example of what I came up with:
static void Main() {
// Person with ID 1 already exists in database.
// 1. Update the Age and Name.
Person person = new Person();
person.Id = 1;
person.Age = 18;
person.Name = "Alex";
// 2. Do not update the NI. I want to preserve that value.
// person.NINumber = "123456";
Update(person);
}
static void Update(Person updatedPerson) {
var context = new PersonContext();
context.Persons.Attach(updatedPerson);
var entry = context.Entry(updatedPerson);
entry.Property(e => e.Name).IsModified = true;
entry.Property(e => e.Age).IsModified = true;
// Boom! Throws a validation exception saying that the
// NI field is required.
context.SaveChanges();
}
public class PersonContext : DbContext {
public DbSet<Person> Persons { get; set; }
}
public class Person {
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Age { get; set; } // this is contrived so, yeah.
[Required]
public string NINumber { get; set; }
}
What am I doing wrong?
State
property toEntityState.Modified
does not help. Thanks anyway. – Denysecontext.Entry(updatedPerson).State = EntityDtate.Modified;
but that is assumingupdatedPerson
is an EF object, and not just a normal class object. – LeprechaunNINumber
property (in this case it would becomenull
and cause a validation error). This is what I am trying to avoid. – Denyse