Background:
- Entity Framework 4
- Silverlight 4
- RIA services
- MSSQL Server 2008
I have an entity that has a String property named Description.
In database it maps to the NOT NULL NVARCHAR(200)
.
Problem:
When I try to insert a new row of that entity, this is what I do:
MyExampleEntity entity = new MyExampleEntity()
{
Name = "example",
Description = "" // NOTE THIS LINE!
};
DatabaseContext db = new DatabaseContext();
db.MyExampleEntities.Add(entity);
db.SubmitChanges();
This, however, causes an exception saying "The Description field is required."
Question:
Should not the "empty string" be simply that - a string with zero characters?
I believe only Description = null
should be treated as providing no value.
- Why is my string, which has a value (although its length is 0), considered to be as if I have omitted the value?
- On what level does this conversion happen? On RIA, on EF or in MSSQL?
- Is there a way to make a description have zero-length value when I set the
Description to ""
and cause an exception whenDescription = null
(having no value)?
[Required]
attribute might collide with FluentValidation rules if you're using those, since these can add the attribute as well, and you can only have one instance of the attribute at a time (https://mcmap.net/q/410004/-fluent-validations-error-validation-type-names-in-unobtrusive-client-validation-rules-must-be-unique). I was able to get around this and allow empty strings by dropping the[Required]
attribute from the MetadataType class and adding a conditional rule to the validation:RuleFor(x => x.Field).Etc(...).When(x => !string.IsNullOrWhitespace(x.Field);
– Wes