Databases Reference
In-Depth Information
var employee = new Employee();
employee.BirthDate = new DateTime(74, 1, 1);
context.Employees.AddObject(employee);
context.SaveChanges();
}
}
StringLengthAttribute
SQL Server allows you to specify the maximum length of values that can be stored in
columns of string types such as
CHAR
and
VARCHAR
. However, the errors it reports when
encountering values that are too long to be stored in the underlying database column
without data truncation do not include the actual column name. This makes debugging of
truncation errors unnecessarily difficult. Fortunately, the
StringLengthAttribute
can be
used to validate the string length before the data is sent to the database server. Here is
how you can extend the
ProductName
property of the
Product
entity class:
[Required]
[StringLength(40, MinimumLength = 2]
public object ProductName;
The
StringLengthAttribute
allows you to specify both minimum and maximum length
that a string value can have. The
maximum
length is required and specified as the first
argument of the constructor. The
minimum
length is optional and has to be specified
explicitly by including the name of the
MinimumLength
property in the constructor.
The following test method verifies how the
StringLengthAttribute
works by initializing the
ProductName
property with a string that consists of 41 characters—one character too long. As
you would expect from a validation attribute, this code throws a
ValidationException
,
which unlike the low-level
SqlException
includes the display name of the column that
caused the problem:
[TestMethod]
[ExpectedValidationException(MemberName =
“ProductName”
)]
public void ProductName_MustBe40CharactersOrLess()
{
using (new TransactionScope())
using (var context = new NorthwindEntities())
{
var product = new Product();
product.ProductName = new String('T', 41);
context.Products.AddObject(product);
context.SaveChanges();
}
}