I am working with Entity Framework with mvc and on the client side I have implemented a Select2 for this I have created the following model:
public class Select2
{
public int id { get; set; }
public string text { get; set; }
public Object[] data { get; set; }
}
The id and text properties are mandatory for a select2, I have created the data property to save all the data that I extract in the query, since previously it only returned the id and the name that were in the id and text properties, so I want to add a array of objects to hold all the other columns of my query.
I use this code:
[HttpGet]
public async Task<ActionResult> GetMesa(string q)
{
try
{
if (String.IsNullOrEmpty(q) || String.IsNullOrWhiteSpace(q))
{
return Json(new { respuesta="El filtro no puede ser nulo o un espacio en blanco /n" }, JsonRequestBehavior.AllowGet);
}
else
{
var items = await db.Mesa.Where(x => x.NombreMesa.ToLower().StartsWith(q.ToLower()))
.Select(x => new Select2()
{
id = x.MesaID,
text = x.NombreMesa,
data = new object[] { x.MesaID, x.NumeroMesa, x.NombreMesa, x.CapacidadMesa, x.AccionMesa, x.PisoMesa }
})
.ToListAsync();
return Json(new { respuesta = "OK", items = items },JsonRequestBehavior.AllowGet);
}
}
catch (Exception e)
{
return Json(new {respuesta = "MesasController => GetMesa \n" + e.Message + e.InnerException}, JsonRequestBehavior.AllowGet);
}
}
I get the following error when I assign the value to items :
Cannot convert type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports conversion of EDM primitives or enumeration types.
How can I solve that? Or should I just use another way?
When the lambda expression tree is built, an attempt will be made to convert the values to an array of objects, which upon validation ( ValidateAndAdjustCastTypes ) detects that this type of conversion is not allowed.
Try passing an anonymous method :
I leave you the link of the method ( ValidateAndAdjustCastTypes ) that performs the validation and throws the exception.
I have replicated your example and it does indeed throw an exception of type
NotSupportedException
: