Databases Reference
In-Depth Information
EnumDataTypeAttribute
Consider the
OrderStatus
enumerated type (or
enum
for short) defined in the sample
project for the Order entity:
public enum OrderStatus: byte
{
Draft = 0,
Submitted = 1,
Paid = 2,
Fulfilled = 3
}
Due to the limitations in the current version of the Entity Framework, the
OrderStatus
property of the Order entity class is actually of type
Byte
and allows values other than the
0, 1, 2, and 3 defined in the enum. Even without the limitation, you could cast any value
of a compatible numeric type, such as 10 of type
Byte
in this case, to the enum type,
OrderStatus, and store it a variable or property of the enum type.
NOTE
The .NET Framework specifically allows variables of an enum type to store values that
are not defined in the enum. This allows class library developers to add new items to
existing enum types without breaking binary compatibility with applications that were
compiled with the original version of a class library.
The
EnumDataTypeAttribute
verifies that a value is actually defined in the specified
enumerated type. You can apply it to the
OrderStatus
property of the
Order
class to
ensure that only values defined in the
OrderStatus
enum can be stored in it:
[
EnumDataType(typeof(OrderStatus))
]
public object OrderStatus { get; set; }
You can verify that this attribute works by writing the following test. It sets the
OrderStatus
property with the value 10, which is
not defined
in the
OrderStatus
enum. As
expected, the validation code in the
SaveChanges
method detects this error and throws
the
ValidationException
:
[TestMethod]
[ExpectedValidationException(MemberName =
“OrderStatus”
)]
public void OrderStatus_RejectsInvalidValues()
{
using (new TransactionScope())
using (var context = new NorthwindEntities())
{
var order = CreateOrder();
order.OrderStatus = 10;
context.Orders.AddObject(order);