Object reference not set as an instance of an object. Asp.net MVC

3

Add two more fields to the beneficiary class and I made the migrations now it is showing me this error.

//Model 
[Table("Beneficiarios")]
    public class Beneficiario
    {
        [Key]
        public  int beneficiarioId { get; set; }
        public string nombreBeneficiario { get; set; }
        public string apellidoBeneficiario { get; set; }
        public string cedula { get; set; }
        public string resolucion { get; set; }
        public string nombreBeneficio { get; set; }
        public string siglas { get; set; }
        public string tipoBeca { get; set; }
        public string estado { get; set; }
        public int mesInicio { get; set; }
        public int anoInicio { get; set; }
        public int mesVence { get; set; }
        public int anoVence { get; set; }
        public int montoTotal { get; set; }
        public decimal montoOtorgado { get; set; }
        public decimal montoPendiente { get; set; }
        public string fuente { get; set; }
        public string codigoPlastico { get; set; }
        public string fotoUrl { get; set; }
        public string firmaUrl { get; set; }
        public bool impreso { get; set; }
        public string carnetFechaImpreso { get; set; }
        public string carnetUsuarioImpreso { get; set; }
//Controller
 //
        // POST: FotoCarnet/GuardarFoto
        [HttpPost]
        public RedirectToRouteResult GuardarFoto(FormCollection form)
        {
            string cedula = form["cedula"];
            string imagenBase64 = form["image"];
            string imageSource;
            Image imagen;
            Beneficiario beneficiario = new Beneficiario();
            string[] partesCedula = cedula.Split('-');
            string nombreFoto = partesCedula[0] + "/" + partesCedula[1] + "/" + cedula + ".jpg";
            string folderRaiz = Server.MapPath("~/Fotos/" + partesCedula[0]);
            string subFolder = Server.MapPath("~/Fotos/" + partesCedula[0] + "/" + partesCedula[1]);
            string rutaFoto = Server.MapPath("~/Fotos/" + nombreFoto);

            if (imagenBase64 != null)
            {
                imageSource = String.Format("data:image/jpg;base64,{0}", imagenBase64);
                imagen = Base64ToImage(imagenBase64);

                if (!Directory.Exists(folderRaiz))
                {
                    System.IO.Directory.CreateDirectory(folderRaiz);
                }
                if (!Directory.Exists(subFolder))
                {
                    System.IO.Directory.CreateDirectory(subFolder);
                }
                imagen.Save(rutaFoto, System.Drawing.Imaging.ImageFormat.Jpeg);

                var queryBeneficiario = from b in _dbContext.Beneficiarios
                                        where b.cedula == cedula
                                        select b;

                beneficiario = queryBeneficiario.First[![introducir la descripción de la imagen aquí][1]][1]();
                beneficiario.fotoUrl = nombreFoto;
                _dbContext.SaveChanges();

                RevertirValidarImpresion(cedula);
            }

            return RedirectToAction("Resultados", "FotoCarnet", new { cedula = cedula });
        }

I'm what the query brings me, but still asks me to instantiate

    
asked by e.herrera 26.07.2016 в 17:10
source

3 answers

1

The value you are trying to get for beneficiario is null, you have to check because you are getting a null value of queryBeneficiario.FirstOrDefault() :

 beneficiario = queryBeneficiario.FirstOrDefault();

By having a null value, you can not access the property fotoUrl since the instance of beneficiario has a null value:

  beneficiario.fotoUrl = nombreFoto;

for this reason you get the error message:

  

Object reference not set as an instance of an object

    
answered by 26.07.2016 / 17:21
source
1

This happens because when doing the linq this does not return any entity, it means that there is no entity with the cedula that you define in the filter

var beneficiario = (from b in _dbContext.Beneficiarios
                            where b.cedula == cedula
                            select b).FirstOrDefault();

if(beneficiario != null)
{
    beneficiario.fotoUrl = nombreFoto;
    _dbContext.SaveChanges();
}

You should validate if no beneficiary is found with the cedula that you apply in the "Where"

    
answered by 26.07.2016 в 17:25
0

Validates if the object is different from null before starting to use it after each query. The controls are never over and do not load your code.

if(objeto!=null)
    //Código si el objeto está correcto.
else
    //Código si el objeto es null. Puedes lanzar una exception!

As well as others indicate, valid if there is someone with that identification - Condition Controls again - but never use an object that is filled by a user without first confirming if it has presumably correct information. Always confirm.

Greetings

    
answered by 31.08.2016 в 15:29