LINQ 2 SQL 查询不适用于函数调用
- 作者: Oculus
- 来源: 51数据库
- 2022-12-13
问题描述
我很确定这个问题已经被问过好几次了,我很抱歉再次提出这个问题,但我做了一些研究,不幸的是我没有在互联网上找到我的乐趣......
I am quite sure this question has already been asked several times and I do apolgize for asking it once again, but I made a few research and unfortunately I did not find my pleasure on the internet...
我有一个像这样的 IQueryable :
I have a IQueryable like this :
triggers = triggers.Where(t => GetIdFromName(t.Name) == filter.Id.ToString());
函数 GetIdFromName 获取部分名称以检索 Id :
The function GetIdFromName get a part of the name to retrieve the Id :
public string GetIdProfiloFromName(string name)
{
return name.Substring(name.IndexOf(NameFirstSeparator)+1,name.IndexOf(NameSecondSeparator)-name.IndexOf(NameFirstSeparator)-1);
}
我知道这并不好,但这是我迄今为止所能做到的最好的.我的问题是使用这两个语句不允许使用 Linq to sql.应用程序抛出一个错误,但这是可以的:
I know it is not nice, but it is the best I could managed to do so far. My question is that using Linq to sql is not permitted using these two statements. The application throws an error, whereas this is ok :
triggers = triggers.Where(t => t.Name.Substring(t.Name.IndexOf(NameFirstSeparator) + 1, t.Name.IndexOf(NameSecondSeparator) - t.Name.IndexOf(NameFirstSeparator) - 1) == filter.Id.ToString());
我怀疑函数 GetIdFromName 应该给出与字符串不同的东西,但我真的很想知道是什么以及如何......
I suspect that the function GetIdFromName should give something different than a string, but I really wonder what and how...
感谢您的启发,
约安
更新我目前的理解:
我不能做我想做的事,因为为了做到这一点,我需要做这样的事情:
I cannot do what i wanted, because in order to do so I would need to do something of this kind :
static Expression<Func<Trigger,string, bool>> IsId = (a,b) => a.name.Substring(a.name.IndexOf(NameFirstSeparator) + 1, a.name.IndexOf(NameSecondSeparator) - a.name.IndexOf(NameFirstSeparator) - 1)==b;
但这不会进入
triggers = triggers.Where(func<Trigger,bool>);
我可以设法做到这一点,但我必须从我的数据库中获取所有结果才能在内存中执行我的测试.
And I could manage to do it, but I would have to get all the results from my database to perform my test in memory.
非常感谢大家,你让我明白了这一点!!
Thanks a lot all, you made this get really clear to me!!
推荐答案
LINQ 2 SQL 正在将您的查询转换为 表达式树,然后将该表达式树翻译成 SQL.由于您的自定义函数没有与 SQL 相关的函数,因此它不知道如何翻译并抛出异常.
LINQ 2 SQL is converting your query into an expression tree, and then translating that expression tree into SQL. Since your custom function doesn't have an SQL correlated function, it doesn't know how to translate it and throws an exception.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
