Hello Team,
Please am getting the below error from my controller, kindly assist me
Additional information: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
C#
public ActionResult Index()
{
RoomViewModel objRoomViewModel = new RoomViewModel();
objRoomViewModel.ListOfBookingStatus = (from obj in objHotelDbEntities.BookingStatus
select new SelectListItem()
{
Text = obj.BookingStatus,
Value = obj.BookingStatusId.ToString(),
Selected = false
}).ToList();
objRoomViewModel.ListOfRoomRtype = (from obj in objHotelDbEntities.RoomTypes
select new SelectListItem()
{
Text = obj.RoomTypeName,
Value = obj.RoomTypeId.ToString(),
Selected = false
}).ToList();
return View(objRoomViewModel);
}
Naimish MakwanaRank #324 · 7.7K reputationPosted Jul 20, 2023, 8:21 AM EDT
The error you are encountering is related to Entity Framework and LINQ to Entities. The issue arises because the
ToString()method is being used within the LINQ query, and Entity Framework is unable to translate it into a valid SQL query.To resolve this error, you should move the
ToList()method to execute the query against the database before calling theToString()method. Here's how you can modify your code to fix the issue:public ActionResult Index() { RoomViewModel objRoomViewModel = new RoomViewModel(); // Execute the first LINQ query against the database and get the results as a list. List bookingStatusList = objHotelDbEntities.BookingStatus .Select(obj => new SelectListItem() { Text = obj.BookingStatus, Value = obj.BookingStatusId.ToString(), // Moved ToString() outside the query Selected = false }).ToList(); // Execute the second LINQ query against the database and get the results as a list. List roomTypeList = objHotelDbEntities.RoomTypes .Select(obj => new SelectListItem() { Text = obj.RoomTypeName, Value = obj.RoomTypeId.ToString(), // Moved ToString() outside the query Selected = false }).ToList(); objRoomViewModel.ListOfBookingStatus = bookingStatusList; objRoomViewModel.ListOfRoomRtype = roomTypeList; return View(objRoomViewModel); }Thanks
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jul 21, 2023, 12:13 PM EDT
Hello Naimish, please I did the correction as you indicated but the error still exist.
Additional information: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.