2

MVC 3内の作成ビューにコンボボックスを設定しようとしています。これは、これまでに行ったことです。

    public ActionResult Create()
    {
        var db = new ErrorReportingSystemContext();
        IEnumerable<SelectListItem> items = db.Locations
          .Select(c => new SelectListItem
          {
              Value =c.id,
              Text = c.location_name
          });
        ViewBag.locations = items;
        return View();
    } 

ただし、実行しようとすると、コンパイルエラーが発生します。

Cannot implicitly convert int to string

この投稿で私それを読んだ

Value = SqlFunctions.StringConvert((double)c.ContactId)

問題は修正されますが、それを実行しようとすると、次のエラーが発生します。

the name 'SqlFunctions' does not exist in the current context

私は何を間違っているのですか?

アップデート:

実行Value = c.id.ToString()するとエラーが発生します:

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

4

3 に答える 3

6

.ToString()あなたの問題は、EFがキャストを文字列またはメソッドに変換できないことです。

.AsEnumerable()したがって、を選択する前に、DBクエリを(を呼び出して)SelectListItem評価する必要があります。

IEnumerable<SelectListItem> items = db.Locations
      .AsEnumerable()
      .Select(c => new SelectListItem
      {
          Value = c.id.ToString(),
          Text = c.location_name
      });

ただし、生成されたSQLクエリは次のようになるため、このアプローチにはパフォーマンス上の問題がいくつかあります。

SELECT * FROM Locations ...

したがって、Locationsテーブルに50列がある場合、EFはそれらすべてからデータをロードしますが、後で必要になるのは2列のデータのみです。

最初に匿名型を選択し、次に SelectListItemsを選択することで、どの列をロードするかをEFに指示できます。

IEnumerable<SelectListItem> items = db.Locations
      .Select(c => new
      {
          c.id,
          c.location_name
      });
      .AsEnumerable()
      .Select(c => new SelectListItem
      {
          Value = c.id.ToString(),
          Text = c.location_name
      });

そして、生成されたクエリは次のようになります。

 SELECT id, location_name FROM Locations
于 2012-09-17T19:40:33.753 に答える
0

Value文字列を予期しているのに、文字列を格納しようとしているのはおそらく不平ですint

試す:

Value = c.id.ToString(),
于 2012-09-17T16:07:44.497 に答える
0
foreach (var item in db.table.tolist())
{
                Combobox.Items.Add(item.field.tostring());
}
于 2012-09-17T16:15:56.357 に答える