Reputation: 8171
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?
Upvotes: 1
Views: 141
Reputation: 16049
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
Upvotes: 0
Reputation: 101443
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).
Upvotes: 4
Reputation: 416
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
Upvotes: 0
Reputation: 117
Assign a value to the Number field.
var doc = new Document() { Id = docId, Version= version, Number = "SomeValue" };
Upvotes: 0