Invoke an Expression in a Select statement - LINQ to Entity Framework

纵然是瞬间 提交于 2019-12-06 06:54:26

问题


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.



来源:https://stackoverflow.com/questions/3348099/invoke-an-expression-in-a-select-statement-linq-to-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!