Is it possible to convert an Object result into an Arrangement in C #?

0

I have the following method:

public List<AnfitrionDto> Seleccionar()
        {
            List<AnfitrionDto> ret = new List<AnfitrionDto>();
            VisitantesEntities db = new VisitantesEntities();            
            Anfitrion[] registros = db.SpAnfitrionConsultar();         
            foreach (var registro in registros)
            {
                ret.Add(AnfitrionAdaptador.ConvertirADto(registro));
            }
        return ret;
    }

In which I make the call of an SP named SpAnfitrion Consult, but it shows me the following error:

Is it possible to convert an Object result into an Arrangement in C #? I think that's the problem I have.

    
asked by Alberto Atencio 03.05.2018 в 22:59
source

2 answers

0

You should use .ToArray ();

public List<AnfitrionDto> Seleccionar()
        {
            List<AnfitrionDto> ret = new List<AnfitrionDto>();
            VisitantesEntities db = new VisitantesEntities();            
            Anfitrion[] registros = db.SpAnfitrionConsultar().ToArray();         
            foreach (var registro in registros)
            {
                ret.Add(AnfitrionAdaptador.ConvertirADto(registro));
            }
        return ret;
    }

Anyway, why do not you use List<T> instead of array?

public List<AnfitrionDto> Seleccionar()
        {
            List<AnfitrionDto> ret = new List<AnfitrionDto>();
            VisitantesEntities db = new VisitantesEntities();            
            var registros = db.SpAnfitrionConsultar().ToList();
            foreach (var registro in registros)
            {
                ret.Add(AnfitrionAdaptador.ConvertirADto(registro));
            }
        return ret;
    }

Greetings!

    
answered by 03.05.2018 / 23:18
source
1

The types that you want to convert seem to be very different, maybe you should use automapper or maybe linq, because beyond what a ObjectResult to an array, the types do not match, you have to map the type SpAnfitrionConsultar_Result to AnfitrionDto is here where linq intervenes

public List<AnfitrionDto> Seleccionar()
{
    List<AnfitrionDto> ret = null;
    using(VisitantesEntities db = new VisitantesEntities())
    {   
        var registros = db.SpAnfitrionConsultar();  

        ret = registros.Select(item => new AnfitrionDto()
        {
            prop1 = item.prop1,
            prop2 = item.prop2,
            //resto
        })
    }

    return ret;
}

in this case in the Select of linq you should map the correct properties of each entity

I would also recommend you take a look at the article

Call Stored Procedure From Entity Framework

If you check the image of step 3 you will see that you can indicate the type that returns the execution of the procedure

    
answered by 03.05.2018 в 23:21