Alex KeySmith
Alex KeySmith

Reputation: 17101

DbContext only validate changed properties

I'm experimenting with updating properties on an entity without getting the entity first from the database.

The trouble is I only wish to update some properties and the entity validator complains that the non-nullable values have not been filled even though I'm not updating those.

Is my only option to turn of the validator?

I'd rather not turn of the validator, as I'd like to validate the properties I'm updating.

TestContext context = new TestContext();

LearningResource learningResource = new LearningResource();

learningResource.LearningResourceID = 132;


DbEntityEntry<LearningResource> entry = context.Entry(learningResource); 

context.LearningResources.Attach(learningResource);

entry.State = EntityState.Unchanged;

learningResource.Title = "alex";

entry.Property(e => e.Title).IsModified = true;

//Only seems to work if I do this.
//context.Configuration.ValidateOnSaveEnabled = false;

context.SaveChanges();

Upvotes: 1

Views: 373

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

That is "a feature". You must turn off global validation and validate every changed property separately.

var result = entry.Property(e => e.Title).GetValidationResult();

I also don't understand why this doesn't happen out of the box.

Upvotes: 2

Related Questions