Databases Reference
In-Depth Information
{
using (new TransactionScope())
using (var context = new NorthwindEntities())
{
var product = new Product();
product.ProductName = string.Empty;
context.Products.AddObject(product);
context.SaveChanges();
}
}
NOTE
In dynamically generated web pages, the
RequiredAttribute
is typically enforced by
the
RequiredFieldValidator
controls created by the field templates.
From a business point of view, requiring each product to have a name probably means
that that it should not be empty. Unlike the
not null
constraint you can use in the data-
base column definition, the
RequiredAttribute
has additional logic for strings that not
only ensures that a string value is not null, but also that it does not contain only white-
space characters. If a non-null, blank string were a valid product name, you could modify
the property definition to set the
AllowEmptyStrings
property of the
RequiredAttribute
to
true
:
[Required(
AllowEmptyStrings = true
)]
public object ProductName { get; set; }
With this new definition of the
ProductName
property, the
RequiredAttribute
prevents
null
values but is happy to accept empty strings as product names. The test method just
shown would now fail because
ValidationException
will not be thrown for the
ProductName
property.
NOTE
All other validation attributes discussed throughout the remainder of this section
treat
null
values as valid. If a property cannot be
null
, you have to place a
RequiredAttribute
on it to prevent
null
values in addition to any other validation
attributes it might need.
RangeAttribute
The
RangeAttribute
verifies that a value falls within a particular range, or more specifi-
cally, that the value is greater than or equal to the minimum value and less than or equal
to the maximum value. In the Product entity, unless you are paying your customers to
take merchandise off your hands, the
UnitPrice
property cannot be less than zero. You
can implement this business rule by applying the
RangeAttribute
to it as shown here: