I want to create a view model that holds list items, and each item will hold the edit and delete action URL so I have the following code:
public ActionResult Index()
{
AdministrationViewModel model = new AdministrationViewModel();
using (var _context = new CamelotFaultManagementEntities())
{
model.FaultTypes = new ListViewModel()
{
ListTitle = AdministrationStrings.FaultTypesAdministrationTab,
AddNewItemURL = "#",
AddNewItemButtonTitle = SharedStrings.Add + " " + SharedStrings.FaultType,
ListItems = _context.FaultTypes.Select(type => new ListItemViewModel() {
ListItemID = type.FaultTypeID,
ListItemName = type.FaultTypeName,
ListItemDescription = type.FaultTypeDescription,
DeleteActionURL = @Url.Action("DeleteFaultType","Administration", new {FaultTypeID = type.FaultTypeID}),
EditActionURL = @Url.Action("EditFaultType", "Administration", new { FaultTypeID = type.FaultTypeID }),
}).ToList()
};
}
return View("Administration",model);
}
The problem is that I receive an error during runtime
LINQ to Entities does not recognize the method 'System.String Action(System.String, System.String, System.Object)' method, and this method cannot be translated into a store expression.
Any way to overcome this... i really don't want to start creating these URLs by myself.
Your problem is here:
DeleteActionURL = @Url.Action("DeleteFaultType","Administration", /*...*/),
EditActionURL = @Url.Action("EditFaultType", "Administration", /*...*/)
LINQ tries to create expression tree, which would be mapped to SQL code, but it doesn't know how to map Url.Action
. One way to fix this would be change Linq to Entities to Linq to Objects, which can be done using ToList()
method on your entity:
ListItems = _context.FaultTypes.ToList().Select(i => ...)