LINQ to Entities 无法识别 MVC 4 中的“System.String ToString()"方法 [英] LINQ to Entities does not recognize the method 'System.String ToString()' method in MVC 4

查看:24
本文介绍了LINQ to Entities 无法识别 MVC 4 中的“System.String ToString()"方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MVC 4,我必须使用 Code First Migrations 更新我的数据库.我想要做的是从数据库表中选择记录,并将它们插入到用户可以选择的下拉列表中.

I'm working with MVC 4 and I have to update my database using Code First Migrations. What I'm trying to do is to select records from a database table, and insert them into a dropdown list where the user can select one.

我有一个我不明白的错误:

I have an error that I don't understand:

LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且该方法无法转换为存储表达式.

控制器:

  public ActionResult Addnew()
        {
            var dba = new DefaultConnection();
            var query = dba.blob.Select(c => new SelectListItem
            {
                Value = c.id.ToString(),
                Text = c.name_company,
                Selected = c.id.Equals(3)
            });
            var model = new Companylist
            {
                xpto = query.AsEnumerable()
            };

            return View(model);
        }

推荐答案

你得到这个错误是因为 Entity Framework 不知道如何在 sql 中执行 .ToString() 方法.因此,您应该使用 ToList 加载数据,然后将其转换为 SelectListItem 为:

You got this error because Entity Framework does not know how to execute .ToString() method in sql. So you should load the data by using ToList and then translate into SelectListItem as:

var query = dba.blob.ToList().Select(c => new SelectListItem
    {
    Value = c.id.ToString(),
    Text = c.name_company,
    Selected = c.id.Equals(3)
});

为了更清楚,实体框架将您对SelectWhere等查询运算符的使用转换为sql查询以加载数据.如果调用 ToString() 之类的方法,实体框架在 sql 中没有等效的方法,它会抱怨.所以这个想法是在数据加载后推迟使用此类功能.ToList, ToArray ETC 强制执行查询从而加载数据.一旦数据被加载,任何进一步的操作(例如 SelectWhere ETC)都将使用 Linq to Objects 对内存中已有的数据执行.

To make it more clear, Entity framework converts your use of query operators such as Select, Where ETC into an sql query to load the data. If you call a method like ToString(), which Entity Framework does not have an equivalent in sql, it will complain. SO the idea is to defer the use of such functions post data load. ToList, ToArray ETC force execution of the query thus loading of data. Once the data is loaded, any further operation (such as Select, Where ETC) is performed using Linq to Objects, on the data already in memory.

这篇关于LINQ to Entities 无法识别 MVC 4 中的“System.String ToString()"方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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