我第一次尝试从 LINQ 到 SQL 到 LINQ 到实体的转换

吉姆·凯

该程序进行了一些非常简单的查找,为支持中文和英文的抽认卡程序生成数据

我删除了 .dbml 文件并创建了一个 Linq to Entities。

原来的查找是这样的:

using (var ceDictionary = new CeDictDataContext(Properties.Settings.Default.ChineseStudyConnection))
            {
                var definitions = from ed in ceDictionary.CeDicts
                                    where ed.Char == WorkTraditional.Text
                                    where ed.Bopo == foundBo[0]
                                    select ed;

                try
                {
                    foreach (var definition in definitions)
                    {
                        textDefinition.Text = definition.English;
                        break;
                    }
                }
                catch (System.Data.StrongTypingException eng)
                {
                    Status.Text = eng.Message;
                    textDefinition.Text = @"DBNull";
                }
            }

经过一番摸索和文档浏览后,我决定只需要更新 using 语句并将“select ed”更改为“select new”

像这样:

using (var ceDictionary = new ChineseStudyEntities())
            {
                var definitions = from ed in ceDictionary.CeDicts
                    where ed.Char == WorkTraditional.Text
                    where ed.Bopo == foundBo[0]
                    select new
                    {
                        ed.English
                    };

                try
                {
                    foreach (var definition in definitions)
                    {
                        textDefinition.Text = definition.English;
                        break;
                    }
                }
                catch (System.Data.StrongTypingException eng)
                {
                    Status.Text = eng.Message;
                    textDefinition.Text = @"DBNull";
                }
            }

好消息是:编译器很高兴,项目构建没有错误。

坏消息是:foreach 语句在运行时崩溃,出现此(我无法理解)错误消息:Message=LINQ to Entities 无法识别方法“System.String get_Item(Int32)”方法,并且此方法无法转换为存储表达式。

这是难以理解的,因为我从数据库中提取的一列是一个字符串,我无法开始猜测为什么“get_Item(Int32)”以某种方式参与其中。('where' 子句中的两列也是字符串。)

佐兰·霍瓦特

我认为您的问题出在这部分:foundBo[0]. 按索引访问字母无法转换为普通 SQL。

尝试使用Substring

var definitions = from ed in ceDictionary.CeDicts
    where ed.Char == WorkTraditional.Text
    where ed.Bopo == foundBo.Substring(0, 1)
    select ed;

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章