在Select语句中调用表达式-LINQ to Entity Framework [英] Invoke an Expression in a Select statement - LINQ to Entity Framework

查看:105
本文介绍了在Select语句中调用表达式-LINQ to Entity Framework的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用在尝试执行select子句时创建的已经存在的Expression构建类,但是我不确定如何为Select将该表达式附加到表达式树上,我尝试执行以下操作:

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
                });

但是我显然收到错误消息,指出实体框架无法将Invoke映射到SQL方法.有办法解决这个问题吗?

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>(字符串名称,int languageID)等效于:

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

我意识到我需要使用ExpressionVisitor来完成此操作,但是我不确定如何使用ExpressionVisitor来更改MemberInitExpression,因此,如果有人知道如何完成此操作,请告诉我.

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.

推荐答案

您需要捕获vars中的表达式.您将无法使用匿名类型.总体思路是这样的:

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);

但这不会:

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

第一个愉快地将GenExpression结果传递给L2E.第二种尝试将GenExpression 本身传递给L2E,而不是结果.

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

因此,您需要引用与表达式相同类型的var.不能隐式地键入这些类型,因此您需要一个实类型作为结果类型.

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.

这篇关于在Select语句中调用表达式-LINQ to Entity Framework的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆