Databases Reference
In-Depth Information
LISTING 12.9 Continued
return Expression.Lambda(property, parameter);
}
private static LambdaExpression BuildParentKeySelector(
Type entityType, string propertyName, Type expectedPropertyType)
{
ParameterExpression parameter = Expression.Parameter(entityType, “parent”);
MemberExpression property = Expression.Property(parameter, propertyName);
if (property.Type == expectedPropertyType)
return Expression.Lambda(property, parameter);
UnaryExpression convertedProperty = Expression.Convert(property,
expectedPropertyType);
return Expression.Lambda(convertedProperty, parameter);
}
private static LambdaExpression BuildResultSelector(
Type childEntityType, Type parentEntityType)
{
ParameterExpression child = Expression.Parameter(childEntityType, “child”);
ParameterExpression parent = Expression.Parameter(parentEntityType, “parent”);
return Expression.Lambda(child, child, parent);
}
}
}
While reading this code, you might have noticed a hard-coded assumption it makes about
the number of primitive columns in the foreign key. This implementation of the Parent
filter template assumes that the primary key of the parent entity consists of a single
column. If your entity model uses compound keys (keys consisting of more than one
column), this filtering logic would produce incorrect results. With static LINQ queries,
compound foreign key values are usually represented with anonymous types, automati-
cally generated by the compiler. With dynamic LINQ queries, this requires emitting anony-
mous types at run time, a large and complex topic that would be difficult to cover in this
book.
Compound keys largely have fallen out of favor with database architects over the past
decade. Even the Northwind sample database, which is more than ten years old, does not
have compound foreign keys. This assumption helps to significantly simplify implementa-
tion of the Parent filter template. However, compound keys have some advantages that
might be important in your application. If that is your situation, take a closer look at the
Dynamic LINQ sample (it is included with this topic's source code). The Dynamic LINQ
includes APIs for emitting anonymous types, which should help to implement a more
sophisticated version of dynamic queries that support compound keys.
 
Search WWH ::




Custom Search