views:

35

answers:

1

I'm trying to use an already existing Expression building class that I made when trying to do a select clause, but I'm not sure how to attach the expression to the expression tree for the Select, I tried doing the following:

var catalogs = matchingCatalogs.Select(c => new
                {
                    c.CatalogID,
                    Name = EntitiesExpressionHelper.MakeTranslationExpression<Catalog>("Name", ApplicationContext.Instance.CurrentLanguageID).Compile().Invoke(c),
                    CategoryName = EntitiesExpressionHelper.MakeTranslationExpression<Category>("Name", ApplicationContext.Instance.CurrentLanguageID).Compile().Invoke(c.Category),
                    c.CategoryID,
                    c.StartDateUTC,
                    c.EndDateUTC
                });

But I obviously get the error stating that the Entity Framework can't map Invoke to a SQL method. Is there a way to work around this?

FYI, EntitiesExpressionHelper.MakeTranslationExpression<T>(string name, int languageID) is equivalent to:

x => x.Translations.Count(t => t.LanguageID == languageID) == 0 ? x.Translations.Count() > 0 ? x.Translations.FirstOrDefault().Name : "" : x.Translations.FirstOrDefault(t => t.LanguageID == languageID).Name

EDIT: I realize that I need to use an ExpressionVisitor to accomplish this, but I'm not sure how to use an ExpressionVisitor to alter the MemberInitExpression, so if anyone knows how to accomplish this, let me know.

A: 

You need to capture the expressions in vars. You won't be able to use anonymous types. The general idea is that this works:

Expression<Func<Foo, Bar>> exp = GenExpression();
var q = matchingCatalogs.Select(exp);

But this will not:

var q = matchingCatalogs.Select(GenExpression());

The first happily passes the result of GenExpression to L2E. The second tries to pass GenExpression itself to L2E, rather than the result.

So you need a reference to a var of the same type as the expression. Those can't be implicitly typed, so you'll need a real type for your result type.

Craig Stuntz
Well the issue isn't the anonymous type, the issue is that I need to inject an expression within another expression essentially, and I would rather do it without having to do the entire MemberInitExpression stuff
Daniel
You may think that my answer has nothing to do with your problem, but your code isn't working, is it?
Craig Stuntz
That's not what I'm saying at all, I'm just saying that's a solution to a different problem. The problem I am faced with is manipulating existing expression trees basically.
Daniel