Linq 与自定义通用扩展方法结合构建错误 - 表达式树可能不包含赋值运算符?

发布于 2025-01-08 15:46:28 字数 684 浏览 0 评论 0原文

我创建了一个通用扩展方法,该方法对对象执行操作并返回该对象:

    public static T Apply<T>(this T subject, Action<T> action)
    {
        action(subject);
        return subject;
    }

我无法在 EntityFramework Linq 查询中使用此扩展方法,因为:

表达式树可能不包含赋值 这是为什么呢

Linq 查询:

var parents = from p in context.Parent
               join phr in context.Child on p.key equals phr.parentkey
               into pr
               select p.Apply(
                      x => x.Children = //The assignment operator that fails to build...
                      pr.ToDictionary(y => y.childkey, y => y.childname));

I've made a generic extension method that executes an action on an object and returns the object after that:

    public static T Apply<T>(this T subject, Action<T> action)
    {
        action(subject);
        return subject;
    }

I'm unable to use this extension method in an EntityFramework Linq query because of:

An expression tree may not contain an assignment operator

Why is this?

The Linq query:

var parents = from p in context.Parent
               join phr in context.Child on p.key equals phr.parentkey
               into pr
               select p.Apply(
                      x => x.Children = //The assignment operator that fails to build...
                      pr.ToDictionary(y => y.childkey, y => y.childname));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逆流 2025-01-15 15:46:28

好吧,撇开赋值运算符不谈,您希望如何将 Apply 方法转换为 SQL?实体框架对此一无所知,也无法深入研究不透明委托。

我怀疑您真正需要做的是将数据库中执行的操作与本地执行的操作分开:

var dbQuery =  from p in context.Parent
               join phr in context.Child on p.key equals phr.parentkey into pr
               select new { p, phr };

var localQuery = dbQuery.AsEnumerable()
                        .Select(pair => /* whatever */);

Well, assignment operator aside, how would you expect your Apply method to be translated into SQL? Entity Framework doesn't know anything about it, and can't delve into opaque delegates, either.

I suspect what you really need to do is separate out the bits to do in the database from the bits to do locally:

var dbQuery =  from p in context.Parent
               join phr in context.Child on p.key equals phr.parentkey into pr
               select new { p, phr };

var localQuery = dbQuery.AsEnumerable()
                        .Select(pair => /* whatever */);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文