The type of the parameter should be something like Expression<Func<Product,object>>
. Also, I think you need your function to return an IEnumerable<Product>
with the properties set.
IEnumerable<Product> myFunction( Expression<Func<Product,object>> selector )
{
var products = new List<Product>();
foreach (var c in dc.Products.Select( selector ))
{
var product = new Product();
foreach (var property in c.GetType().GetProperties())
{
var productProperty = typeof(Product).GetProperty( property.Name );
productProperty.SetValue( product, property.GetValue( c, null ) );
}
products.Add( product );
}
return products;
}
Having said that I think I would probably have a separate model for each combination of properties being returned and use a generic method to return one of those.
IEnumerable<T> ProductPartial<T>( Func<Product,T> selector ) where T : new
{
return dc.Products.ToList().Select( selector );
}
used as
var pricing = repository.ProductPartial( p => new PricingModel( p ) );
Note: After thinking about it a little, if you are going to return a separate model, I think you may need to realize the query before you can do the conversion to the model anyway. In that case a Func<Product,T>
is probably most appropriate -- I've thrown an explicit ToList() in to make sure that the query is realized first so the select doesn't fail. If it were a Where
clause, that would be different. Even though this is slightly less efficient from a data transfer perspective (you're retrieving all the properties), I still prefer using using the specific model if you feel like you need to put the selection in the repository. Since you're only selecting part of the properties it feels wrong to pretend that you have an actual Product instance when you really don't.