A
Andrus
I tried to use association property in Marc Select() extension method but
got exception
in Bind() call
Property 'Customer.ContactName' is not defined for type 'nwind.Order'"
How to fix ?
Andrus.
Northwind northwind = CreateDB();
var orders = northwind.GetTable<Order>();
var q = orders.Select(
new string[] {"OrderID",
"Customer.ContactName" });
// should generate:
//var q = from order in orders
// select new {
// order.OrderID,
// order.Customer.ContactName
// };
var list = q.ToList();
// Extension methor created by Marc Gravell
public static class SelectUsingSingleProjection {
public static IQueryable<T> Select<T>(this IQueryable<T> source, params
string[] propertyNames)
where T : new() {
if (source == null) throw new ArgumentNullException("source");
if (propertyNames == null) throw new
ArgumentNullException("propertyNames");
Type type = typeof(T);
var sourceItem = Expression.Parameter(type, "t");
var newExpr = Expression.New(type.GetConstructor(Type.EmptyTypes));
var bindings = propertyNames.Select<string, MemberBinding>(
name => Expression.Bind(
type.GetProperty(name),
Expression.Property(sourceItem, name))
).ToArray();
return source.Select(Expression.Lambda<Func<T, T>>(
Expression.MemberInit(newExpr, bindings), sourceItem));
}
got exception
in Bind() call
Property 'Customer.ContactName' is not defined for type 'nwind.Order'"
How to fix ?
Andrus.
Northwind northwind = CreateDB();
var orders = northwind.GetTable<Order>();
var q = orders.Select(
new string[] {"OrderID",
"Customer.ContactName" });
// should generate:
//var q = from order in orders
// select new {
// order.OrderID,
// order.Customer.ContactName
// };
var list = q.ToList();
// Extension methor created by Marc Gravell
public static class SelectUsingSingleProjection {
public static IQueryable<T> Select<T>(this IQueryable<T> source, params
string[] propertyNames)
where T : new() {
if (source == null) throw new ArgumentNullException("source");
if (propertyNames == null) throw new
ArgumentNullException("propertyNames");
Type type = typeof(T);
var sourceItem = Expression.Parameter(type, "t");
var newExpr = Expression.New(type.GetConstructor(Type.EmptyTypes));
var bindings = propertyNames.Select<string, MemberBinding>(
name => Expression.Bind(
type.GetProperty(name),
Expression.Property(sourceItem, name))
).ToArray();
return source.Select(Expression.Lambda<Func<T, T>>(
Expression.MemberInit(newExpr, bindings), sourceItem));
}