简体   繁体   中英

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

I am using following code in my controller

BlueBusDB_Context db = new BlueBusDB_Context();
List<SelectListItem> li =new List<SelectListItem>();

li = db.M_BLUEBUS_STATES.Select(s => new SelectListItem {Text = s.STATE_NAME, Value = Convert.ToString(s.STATE_CODE)}).ToList();

ViewBag.State = li;
return View();

then in my create View I want to bind the dropdown and I am using as bellow

@Html.DropDownList("State",ViewBag.State as List<SelectListItem>)

I am getting the above error..

Linq to Entities does not support Convert (see supported funuctions )

I would first create an anonymous type and then convert into SelectListItems to better seperate concerns a little bit:

li = db.M_BLUEBUS_STATES
       .Select(s => new { s.STATE_NAME, s.STATE_CODE })
       .AsEnumerable()
       .Select(x => new SelectListItem { Text = x.STATE_NAME, Value = x.STATE_CODE.ToString()})
       .ToList();

You need to use the regular ToString method instead of the one from Convert class:

li = db.M_BLUEBUS_STATES.Select(s => new SelectListItem {
     Text = s.STATE_NAME, 
     Value = s.STATE_CODE.ToString()
}).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question LINQ to Entities does not recognize the method 'System.String ToString(Int32)' method, and this method cannot be translated into a store expression LINQ to Entities does not recognize the method 'Int32 Int32(System.String)' method, and this method cannot be translated into a store expression LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression LINQ to Entities does not recognize the method 'System.String get_Item(Int32)' 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 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 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(Int32)' method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM