I am trying to attach an object that exists in the database to new DbContext, modify a single value (property: SubmissionGrpID, which is a foreign key) and then save the changes to the database. I am trying to do this without having to load the whole entity into the DbContext from the database.
I have already seen the question: How to update only one field using Entity Framework? but the answers did not help me.
The property: ID in the PnetProdFile table is the only column used in the primary key for that table. The code I am using is below:
using (SomeEntities db = new SomeEntities())
{
foreach (var id in FileIds)
{
PnetProdFile file = new PnetProdFile();
file.ID = id; // setting the primary key
file.SubmissionGrpID = 5; // setting a foreign key
db.PnetProdFiles.Attach(file);
var entry = db.Entry(file);
entry.Property(e => e.SubmissionGrpID).IsModified = true;
}
db.SaveChanges();
}
When I run the code, I get the following exception:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Then, after adding in the following line of code before I SaveChanges():
var errors = db.GetValidationErrors();
I get all the Not Null fields as required values for the PnetProdFile table in the Validation Errors. One way to prevent validation errors is to set
db.Configuration.ValidateOnSaveEnabled = false;
but then that prevents validation on the entire entity, even on properties that could have been updated.
So, to summarise, I am trying to update an object which already exists in the database without loading the related record from the database, and only get validation errors on properties that have been changed. How can this be done?