C# LINQ to Entities 无法识别 MVC 4 中的“System.String ToString()”方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18233495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:35:38  来源:igfitidea点击:

LINQ to Entities does not recognize the method 'System.String ToString()' method in MVC 4

c#asp.netasp.net-mvcasp.net-mvc-4ef-migrations

提问by user2232273

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.

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

I have an error that I don't understand:

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

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

Controller:

控制器:

  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);
        }

采纳答案by Varun K

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 ToListand then translate into SelectListItem as:

您收到此错误是因为实体框架不知道如何.ToString()在 sql 中执行方法。因此,您应该使用加载数据ToList,然后将其转换为 SelectListItem 为:

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

Edit: To make it more clear, Entity framework converts your use of query operators such as Select, WhereETC 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, ToArrayETC force execution of the query thus loading of data. Once the data is loaded, any further operation (such as Select, WhereETC) is performed using Linq to Objects, on the data already in memory.

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

回答by Leandro Soares

What if... you use:

如果...你使用:

Value = c.id + "",

instead of

代替

Value = c.id.ToString(),

Edit

编辑

With this option, you are not retrieving all data from Database

使用此选项,您不会从数据库中检索所有数据

回答by Ali7091

just use delegate :

只需使用委托:

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

回答by LCJ

Following is how I do it to display as a SelectList.

以下是我如何将其显示为 SelectList。

 public List<BlobEntity> GetBlobs()
    {
        List<BlobEntity> blobs = null;
        using (var db = new MyDBEntities())
        {
            blobs = (from b in db.blobs
                     where b.id > 0 //Example filter
                     select new BlobEntity
                     {
                         ID = b.id,
                         CompanyName = b.name_company
                     }
                     ).ToList();

        }
        return blobs;
    }

   public static SelectList GetBlobsSelectList()
    {
        MyBL theBL = new MyBL();
        List<BlobEntity> blobEntites = theBL.GetBlobs();
        var listItems = blobEntites
             .Select(x => new SelectListItem { Text = x.CompanyName,
                                                Value = x.ID.ToString()
                                             })
             .ToList();
        SelectList blobsSelectList = new SelectList(listItems.AsEnumerable(), "Value", "Text");
        return blobsSelectList;
    }

   public class BlobEntity
   {
       public int ID { get; set; }
       public string CompanyName { get; set; }
   }

The current accepted answer (by @VarunK) is okay if you are selecting all records and all columns. However, if that is not the case, it is better to do a projection with required columns and records before applying ToList().

如果您选择所有记录和所有列,当前接受的答案(@VarunK 提供)是可以的。但是,如果情况并非如此,则最好在应用之前对所需的列和记录进行投影ToList()

Take a look at Why LINQ to Entities does not recognize the method 'System.String ToString()?.

看看为什么 LINQ to Entities 不能识别方法 'System.String ToString()?.

Other references: Problem with converting int to string in Linq to entities

其他参考:在 Linq 中将 int 转换为字符串到实体的问题