0
[HttpPost]
    public ActionResult Edit(FormCollection form)
    {
        // Get movie to update
        var id = Int32.Parse(form["id_foto"]);
        var fotoToAdd = _db.foto.First(m => m.id_foto == id);

        // Deserialize (Include white list!)
        TryUpdateModel(fotoToAdd, new string[] { "descricao" },    form.ToValueProvider());

        //Here I try to change my foreign key, but i get this exception: "The property 'id_album' part of the key information of the object and can not be changed."
        fotoToAdd.id_album = Convert.ToInt32(form["id_album"]);

        //file upload 
        if (Request.Files.Count > 0)
        {
            int tamanho = (int)Request.Files[0].InputStream.Length;
            byte[] arq = new byte[tamanho];
            Request.Files[0].InputStream.Read(arq, 0, tamanho);
            byte[] arqUp = arq;
            fotoToAdd.imagem = arqUp;
        }

        //Validation
        if (String.IsNullOrEmpty(fotoToAdd.descricao))
            ModelState.AddModelError("Descrição", "Ops... campo obrigatório");
        if (String.IsNullOrEmpty(fotoToAdd.id_album.ToString()))
            ModelState.AddModelError("Album", "Ops... campo obrigatório");
        if (fotoToAdd.imagem == null)
            ModelState.AddModelError("Foto", "Ops... campo obrigatório");

        //If success, Update
        if (ModelState.IsValid)
        {
            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        //Else, return view
        return View(fotoToAdd);
    }

//Here I try to change my foreign key, but i get this exception: "The property 'id_album' part of the key information of the object and can not be changed."

fotoToAdd.id_album = Convert.ToInt32(form["id_album"]);

I have been researching how to do this, but am having difficulty, how do I make this update operation

  • don't you have the navigation property something like fotoToAdd.album in foto class? If you have it you can set like fotoToAdd.album=_db.album.first... – Jayantha Lal Sirisena Jun 01 '11 at 03:34

1 Answers1

0

This will be a help for you Entity Framework: Setting a Foreign Key Property

Community
  • 1
  • 1
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92