-->

Invoke an Expression in a Select statement - LINQ

2019-04-12 00:08发布

问题:

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.

回答1:

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.