如何使用ASP.NET MVC 2 + Entity更改外键

问题描述

||
[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,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);
    }
//这里我尝试更改外键,但出现以下异常:\“对象的键信息的属性\'id_album \'部分,不能更改。\” fotoToAdd.id_album = Convert.ToInt32(form [\“ id_album \”]); 我一直在研究如何执行此操作,但是遇到困难,如何进行此更新操作     

解决方法

        这对您有帮助 实体框架:设置外键属性     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...