Unable to convert type 'System.Int32' to type 'System.Object'

0

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, the data property was created 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 properties id and text then I want add an array of objects to save 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);
        }
    }

The following error jumps me when I assign the value to items :

  

Can not convert the type 'System.Int32' to the type 'System.Object'. LINQ to Entities only supports the conversion of enumeration types or EDM primitives.

How can I solve it? Or should I just use another form?

    
asked by denifer santiago fernandez 26.12.2018 в 17:15
source

1 answer

1

When the lambda expression tree is built, it will try to convert the values to an array of objects, which will be validated ( ValidateAndAdjustCastTypes ) detects that this type of conversion is not allowed.

Try passing a anonymous method :

var items = await db.Mesa.Where(x => x.NombreMesa.ToLower().StartsWith(q.ToLower()))
    .Select(delegate(Mesa x) {
        return new Select2()
        {
            id = x.MesaID,
            text = x.NombreMesa,
            data = new object[] { x.MesaID, x.NumeroMesa, x.NombreMesa, x.CapacidadMesa, x.AccionMesa, x.PisoMesa }
        };
    })
    .ToListAsync();

I leave the method link ( ValidateAndAdjustCastTypes ) that performs the validation and throws the exception.

I have replicated your example and in effect throws an exception of NotSupportedException :

  

Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ   to Entities only supports casting EDM primitive or enumeration types.

     

at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter. ValidateAndAdjustCastTypes (TypeUsage   toType, TypeUsage fromType, Type toClrType, Type fromClrType) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.GetCastTargetType (TypeUsage   fromType, Type toClrType, Type fromClrType, Boolean   preserveCastForDateTime) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.CreateCastExpression (DbExpression   source, Type toClrType, Type fromClrType) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.ConvertTranslator.TranslateUnary (ExpressionConverter   parent, UnaryExpression unary, DbExpression operand) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression (Expression   linq) at   System.Linq.Enumerable.WhereSelectEnumerableIterator'2.MoveNext () at   System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator'3.Validate (IEnumerable'1   argument, String argumentName, Int32 expectedElementCount, Boolean   allowEmpty, Func'3 map, Func'2 collect, Func'3 deriveName) at   System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator'3.Validate ()   at   System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder.DbExpressionBuilder.CreateNewCollection (IEnumerable'1   elements) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter. NewArrayInitTranslator .TypedTranslate (ExpressionConverter   parent, NewArrayExpression linq) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression (Expression   linq) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MemberInitTranslator.TypedTranslate (ExpressionConverter   parent, MemberInitExpression linq) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression (Expression   linq) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda (LambdaExpression   lambda, DbExpression input) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate (ExpressionConverter   parent, MethodCallExpression call, DbExpression & source,   DbExpressionBinding & sourceBinding, DbExpression & lambda) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SelectTranslator.Translate (ExpressionConverter   parent, MethodCallExpression call) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate (ExpressionConverter   parent, MethodCallExpression linq) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression (Expression   linq) at   System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert () at   System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan (Nullable'1   forMergeOption)

    
answered by 26.12.2018 / 22:11
source