?
Solved

cannot convert from viewmodel to model when saving changes

Posted on 2017-10-12
2
Medium Priority
?
51 Views
Last Modified: 2017-10-12
Good morning,
im getting the error show in the picture bellow, I've seen other examples and it should work, am I doing something wrong?

error.png
my model
 public class Usuario
    {
        public int Id { get; set; }
        
        [Required]
        [StringLength(80)]
        public string Nombres { get; set; }

        [Required]
        [StringLength(40)]
        [Display(Name ="Primer apellido")]
        public string PrimerApellido { get; set; }

        [Required]
        [StringLength(40)]
        [Display(Name = "Segundo apellido")]
        public string SegundoApellido { get; set; }

        [Required]
        [StringLength(30)]
        public string Cedula { get; set; }

        [Required]
        [Display(Name = "Fecha nacimiento ")]
        public DateTime FechaNacimiento { get; set; }

        [Required]
        [StringLength(5)]
        public string Rh { get; set; }

        [Required]
        [StringLength(10)]
        public string Genero { get; set; } 

        [Required]
        [StringLength(200)]
        [Display(Name = "Dirección")]
        public string Direccion { get; set; }

        [Required]
        [StringLength(200)]
        [Display(Name = "Barrio")]
        public string Barrio { get; set; }

                
        public Municipio Municipio { get; set; }

        [Display(Name = "Municipio")]
        public int MunicipioId { get; set; }
        

        [Display(Name ="Telefono fijo")]
        public string TelefonoFijo { get; set; }

        [Required]
        [StringLength(30)]
        public string Celular { get; set; }

        [Required]
        [StringLength(254)]
        public string Correo { get; set; }

        public string Foto { get; set; }

        public string ImagenCC { get; set; }

        public string NumeroIdServicio { get; set; }

        [Required]
        public bool ResidenteAMB { get; set; }

        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        [DefaultValue("getutcdate()")]
        public DateTime? FechaInicioRegistro { get; set; }

        [DefaultValue(false)]
        public Boolean? Validado { get; set; }
                
        public DateTime? FechaFinalizaRegistro { get; set; }

        public int? Pin { get; set; }

    }

Open in new window

my view model
 public class NuevoUsuarioViewModel
    {

        //public Usuario Usuario { get; set; }
        [Required]
        [StringLength(80)]
        public string Nombres { get; set; }

        [Required]
        [StringLength(40)]
        [Display(Name = "Primer apellido")]
        public string PrimerApellido { get; set; }

        [Required]
        [StringLength(40)]
        [Display(Name = "Segundo apellido")]
        public string SegundoApellido { get; set; }

        [Required]
        [StringLength(30)]
        public string Cedula { get; set; }

        [Required]
        [Display(Name = "Fecha nacimiento ")]
        public DateTime FechaNacimiento { get; set; }

        [Required]
        [StringLength(5)]
        public string Rh { get; set; }

        [Required]
        [StringLength(10)]
        public string Genero { get; set; }

        [Required]
        [StringLength(200)]
        [Display(Name = "Dirección")]
        public string Direccion { get; set; }

        [Required]
        [StringLength(200)]
        [Display(Name = "Barrio")]
        public string Barrio { get; set; }


        [Display(Name = "Municipio")]
        public int MunicipioId { get; set; }


        [Display(Name = "Telefono fijo")]
        public string TelefonoFijo { get; set; }

        [Required]
        [StringLength(30)]
        public string Celular { get; set; }

        [Required]
        [StringLength(254)]
        public string Correo { get; set; }      

        [Required]
        public bool ResidenteAMB { get; set; }    

        [Display(Name = "Municipio")]
        public IEnumerable<BiciPublica.Models.Municipio> Municipios { get; set; }
        
    }

Open in new window


thanks in advance for your help.
0
Comment
Question by:Steven
2 Comments
 
LVL 35

Accepted Solution

by:
it_saige earned 2000 total points
ID: 42328924
Since both are different objects, you are going to have to utilize a copy constructor, implicit operator or copy to method; e.g. -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace EE_Q29062184
{
    class Program
    {
        static readonly List<NuevoUsuarioViewModel> views = new List<NuevoUsuarioViewModel>(from i in Enumerable.Range(0, 10) select new NuevoUsuarioViewModel
        {
            Nombres = $"Nombres{i}",
            PrimerApellido = $"PrimerApellido{i}",
            SegundoApellido = $"SegundoApellido{i}",
            Cedula = $"Cedula{i}",
            FechaNacimiento = DateTime.Now.AddMonths(-(9 * i)),
            Rh = $"Rh{i}",
            Genero = $"Genero{i}",
            Direccion = $"Direccion{i}",
            Barrio = $"Barrio{i}",
            MunicipioId = i,
            TelefonoFijo = $"TelefonoFijo{i}",
            Celular = $"Celular{i}",
            Correo = $"Correo{i}",
            ResidenteAMB = (i % 2 == 0),
            Municipios = (from m in Enumerable.Range(0, i + 1) select new Municipio { ID = m, Name = $"Municipo{m}" })
        });

        static void Main(string[] args)
        {
            var models = (from vm in views select (Usuario)vm);
            foreach (var model in models)
                Console.WriteLine(model);

            Console.ReadLine();
        }
    }

    class Usuario
    {
        public int Id { get; set; }
        public string Nombres { get; set; }
        public string PrimerApellido { get; set; }
        public string SegundoApellido { get; set; }
        public string Cedula { get; set; }
        public DateTime FechaNacimiento { get; set; }
        public string Rh { get; set; }
        public string Genero { get; set; }
        public string Direccion { get; set; }
        public string Barrio { get; set; }
        public Municipio Municipio { get; set; }
        public int MunicipioId { get; set; }
        public string TelefonoFijo { get; set; }
        public string Celular { get; set; }
        public string Correo { get; set; }
        public string Foto { get; set; }
        public string ImagenCC { get; set; }
        public string NumeroIdServicio { get; set; }
        public bool ResidenteAMB { get; set; }
        public DateTime? FechaInicioRegistro { get; set; }
        public Boolean? Validado { get; set; }
        public DateTime? FechaFinalizaRegistro { get; set; }
        public int? Pin { get; set; }

        public static implicit operator Usuario(NuevoUsuarioViewModel model)
        {
            var instance = model.CopyTo<NuevoUsuarioViewModel, Usuario>();
            instance.Municipio = model.Municipios.FirstOrDefault(m => m.ID == instance.MunicipioId);
            return instance;
        }

        public override string ToString()
        {
            return $"Id: {Id}; Nombres: {Nombres}; PrimerApellido: {PrimerApellido}; SegundoApellido: {SegundoApellido}; Cedula: {Cedula}; FechaNacimiento: {FechaNacimiento}; Rh: {Rh}; Genero: {Genero}; Direccion: {Direccion}; Barrio: {Barrio}; Municipio: {Municipio}; MunicipioId: {MunicipioId}; TelefonoFijo: {TelefonoFijo}; Celular: {Celular}; Correo: {Correo}; Foto: {Foto}; ImagenCC: {ImagenCC}; NumeroIdServicio: {NumeroIdServicio}; ResidenteAMB: {ResidenteAMB}; FechaInicioRegistro: {FechaInicioRegistro}; Validado: {Validado}; FechaFinalizaRegistro: {FechaFinalizaRegistro}; Pin: {Pin}";
        }
    }

    class NuevoUsuarioViewModel
    {
        public string Nombres { get; set; }
        public string PrimerApellido { get; set; }
        public string SegundoApellido { get; set; }
        public string Cedula { get; set; }
        public DateTime FechaNacimiento { get; set; }
        public string Rh { get; set; }
        public string Genero { get; set; }
        public string Direccion { get; set; }
        public string Barrio { get; set; }
        public int MunicipioId { get; set; }
        public string TelefonoFijo { get; set; }
        public string Celular { get; set; }
        public string Correo { get; set; }
        public bool ResidenteAMB { get; set; }
        public IEnumerable<Municipio> Municipios { get; set; }

        public override string ToString()
        {
            return $"Nombres: {Nombres}; PrimerApellido: {PrimerApellido}; SegundoApellido: {SegundoApellido}; Cedula: {Cedula}; FechaNacimiento: {FechaNacimiento}; Rh: {Rh}; Genero: {Genero}; Direccion: {Direccion}; Barrio: {Barrio}; MunicipioId: {MunicipioId}; TelefonoFijo: {TelefonoFijo}; Celular: {Celular}; Correo: {Correo}; ResidenteAMB: {ResidenteAMB}; Total Municipios: {Municipios.Count()}";
        }
    }

    class Municipio
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public override string ToString()
        {
            return $"ID: {ID}; Name: {Name}";
        }
    }

    static class Extensions
    {
        public static T CopyTo<S, T>(this S source) where T : class, new()
        {
            T instance = Activator.CreateInstance<T>();
            foreach (var s_prop in typeof(S).GetProperties(BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
            {
                var t_prop = instance.GetType().GetProperty(s_prop.Name);
                if (t_prop != null && t_prop.CanWrite)
                    t_prop.SetValue(instance, s_prop.GetValue(source, null));
            }
            return instance;
        }
    }
}

Open in new window

Which produces the following output:Capture.PNG
-saige-
0
 
LVL 1

Assisted Solution

by:Steven
Steven earned 0 total points
ID: 42329169
I'm a noob in mvc and I made a mistake, I was trying to save my view model (vm) instead of my model (elUsuario), I appreciate your help it got me looking into mapping.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
Suggested Courses
Course of the Month13 days, 8 hours left to enroll

750 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question