在 Linq 查询中调用方法 [英] Calling a method inside a Linq query

查看:28
本文介绍了在 Linq 查询中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的表中插入一个名为S"的列,该列将根据从表列中获取的值获取一些字符串值.

I want to insert into my table a column named 'S' that will get some string value based on a value it gets from a table column.

例如:对于每个 ID (a.z) 我想将它的字符串值存储在另一个表中.字符串值是从另一个通过 Linq 查询获取它的方法返回的.

For example: for each ID (a.z) I want to gets it's string value stored in another table. The string value is returned from another method that gets it through a Linq query.

  • 是否可以从 Linq 调用方法?
  • 我应该在同一个查询中做所有事情吗?

这是我需要获取的信息的结构:

This is the structure of the information I need to get:

az 是表 #1 中第一个方块中的 ID,从这个 ID 中我得到表 #2 中的另一个 id,然后我可以得到我需要在列 'S' 下显示的字符串值.

a.z is the ID in the first square in table #1, from this ID I get another id in table #2, and from that I can get my string value that I need to display under column 'S'.

var q = (from a in v.A join b in v.B
    on a.i equals b.j
    where a.k == "aaa" && a.h == 0
    select new {T = a.i, S = someMethod(a.z).ToString()})
    return q;

S = someMethod(a.z).ToString() 导致以下错误:

无法转换类型为System.Data.Linq.SqlClient.SqlColumn"的对象输入System.Data.Linq.SqlClient.SqlMethodCall".

Unable to cast object of type 'System.Data.Linq.SqlClient.SqlColumn' to type 'System.Data.Linq.SqlClient.SqlMethodCall'.

推荐答案

您必须在 Linq-to-Objects 上下文中执行您的方法调用,因为在数据库端该方法调用不会感觉 - 你可以使用 AsEnumerable() 来做到这一点 - 基本上查询的其余部分将被评估为使用 Linq-to-Objects 的内存集合,你可以使用方法按预期调用:

You have to execute your method call in Linq-to-Objects context, because on the database side that method call will not make sense - you can do this using AsEnumerable() - basically the rest of the query will then be evaluated as an in memory collection using Linq-to-Objects and you can use method calls as expected:

var q = (from a in v.A join b in v.B
        on a.i equals b.j
        where a.k == "aaa" && a.h == 0
        select new {T = a.i, Z = a.z })
        .AsEnumerable()
        .Select(x => new { T = x.T, S = someMethod(x.Z).ToString() })

这篇关于在 Linq 查询中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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