1

I have following Entity:

public class Document
{
   public int Id { get; set; }
   [Required]
   public string Number { get; set; }
   public int Version { get; set; }
   //other properties with [Required]
}

I wrote a method to update only Version of one Document:

public void SetDocumentVersion(int docId, int version)
{
   var doc = new Document() { Id = docId, Version= version };
   using (var db = new MyEfContextName())
   {
     db.Documents.Attach(doc);
     db.Entry(doc).Property(x => x.Version).IsModified = true;
     db.SaveChanges();   //<--- get error
}

}

But when I run the method I get following Error:

The Number field is required.

Is there any way to bypass this validation?

1
  • 1
    assign value to Number property while creating instance of Document class. You can see Number field is decorated with [Required]attribute. Error message is self explanatory... Commented May 21, 2018 at 9:30

4 Answers 4

4

You can disable validation on saving changes like this (do this before calling SaveChanges):

db.Configuration.ValidateOnSaveEnabled = false;

Then it should work as you would expect (generate UPDATE query for just Version column).

Sign up to request clarification or add additional context in comments.

Comments

0

Assign a value to the Number field.

var doc = new Document() { Id = docId, Version= version, Number = "SomeValue" };

Comments

0

So, when using Data Annotations on classes that form the tables within your database they are translated into constraints. The Required annotation translates to NOT NULL meaning a value must be supplied.

Remove the Required annotation if you wish the field to be nullable or supply a value.

https://msdn.microsoft.com/en-us/library/jj591583(v=vs.113).aspx

Comments

0

Either remove [Required] attribute to Number property from Document class or assign value to Number property while creating instance of Document class

First approach:

public class Document
{
   public int Id { get; set; }
   //[Required] /*Remove this attribute*/
   public string Number { get; set; }
   public int Version { get; set; }
   //other properties
}

If you can't remove [Required] from model, then assign some value to Number

var doc = new Document() { Id = docId, Version= version, Number = "NotNullStringValue" };

More about required attribute

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.