Databases Reference
In-Depth Information
Although this approach works, accessing values in the weakly typed
object
form prevents
you from taking advantage of the additional validation that compiler could provide for
the values in their original (
Nullable<Byte>
) form. The
DbDataRecord
object returns values
of type
DBNull
because this class was designed in ADO.NET version 1, which did not
support nullable types that were added to the .NET Framework in version 2. Luckily, with
lambda expressions and extension methods introduced in version 3 of the .NET
Framework, you can bring the
DbDataRecord
class into the twenty-first century.
Listing 8.5 shows a static class called
DbDataRecordExtensions
that defines an extension
method called
Get
for the
DbDataRecord
class. This class is available in the
Unleashed.EntityFramework
project of the sample solution accompanying this topic.
LISTING 8.5
DbDataRecord Extensions Methods
using System;
using System.Data.Common;
using System.Linq.Expressions;
namespace Unleashed.EntityFramework
{
public static class DbDataRecordExtensions
{
public static T Get<T>(this DbDataRecord record, Expression<Func<T>> property)
{
string propertyName = ((MemberExpression)property.Body).Member.Name;
object value = record[propertyName];
if (value == DBNull.Value)
return default(T);
else
return (T)value;
}
}
}
The first parameter of the
Get
method is declared with the keyword
this
, which allows
you to call this static method as if it were an instance method of the
DbDataRecord
class.
The second parameter is a lambda expression that you can use instead of hard-coding the
property name as a string. Here's how to change the
ValidateOrderStatus
method to take
advantage of this:
public static ValidationResult ValidateOrderStatus(
byte? newStatus, ValidationContext context)
{
var stateEntry = (ObjectStateEntry)
context.Items[typeof(ObjectStateEntry)];
if (stateEntry.State == EntityState.Modified)
{