为什么我不能在linq查询中调用函数? [英] Why I can't call a function inside a linq query?

查看:223
本文介绍了为什么我不能在linq查询中调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的linq查询(从Linq到Sql):

This is my linq query (Linq to Sql) :

pagina = (from Pagine page in kDataBase.Pagines
          where prova(page.title_it) == urlSuddivisa[i].ToLower()
          select page).FirstOrDefault();

这是我调用的函数(在同一个类中):

and this is the function I call (inside the same class) :

private string prova(string example)
{
    return example;
}             

它说:

不支持将方法'System.String prova(System.String)转换为sql.

there are not supported conversion to sql for the method 'System.String prova(System.String).

我在哪里错了?我该如何解决?

Where am I wrong? And how can I fix it?

推荐答案

由于linq查询被转换为针对您的dB运行的SQL查询,因此无法将您的自定义函数转换为SQL查询.

Since the linq query is converted into a SQL query that runs against your dB it is not able to translate your custom function into a SQL query.

解决问题的替代方法

  • 使用存储过程,并阅读有关在linq中使用存储过程的信息
  • 将数据从SQL检索到内存中,然后根据您的功能对其进行过滤.显然,这里的缺点是您将从数据库中检索到很多行,而不是所需的行.

  • Use a stored procedure and read about using stored procedure in linq
  • retrieve your data from SQL to memory and then filter it based on your function. The disadvantage obviously here is you will be retrieving a lot many number of rows from the database than what is required

var paginas=(from Pagine page in kDataBase.Pagines).ToList().Where(p =>prova(p.title_it) == urlSuddivisa[i].ToLower()).FirstOrDefault();

是您想要的.

另一方面,我猜想您的方法prova所做的不仅仅是返回字符串,否则该函数将完全无用,并且您也可能会放弃该函数.另外,我相信您会使用计数器i向要使用的数组的数据库cos触发多个查询,您始终可以使用IN查询并绕开它,请记住IN查询.

On a side note I am guessing your method prova does more than just returning the string otherwise the function is outright useless and you may as well get rid of the function. Also I believe you are firing multiple queries to the database cos of the array that you are using with a counter i you could always use the IN query and get around it, remember the restriction of the number of element in an IN query.

这篇关于为什么我不能在linq查询中调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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