Home > Software design >  C# MVC context.SaveChanges() do not persist data in database
C# MVC context.SaveChanges() do not persist data in database

Time:08-24

I´ve tried everything, read several questions here, but my code is still not working, and I can´t figure out what I´m doing wrong. The field 'liberado' in database doesn´t change to '1' after the code runned, and I get no errors. Thanks a lot.

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Release(int id)
    {
        Publicacao publicacao =  db.Publicacao.Find(id);
        //Publicacao publicacao = db.Publicacao.Where(a => a.idpublicacao == id).First();
        if (publicacao == null)
        {
            return RedirectToAction("Index");
        }
        db.Publicacao.Attach(publicacao);
        db.Entry(publicacao).State = EntityState.Modified;
        publicacao.liberado = 1;
        db.SaveChanges();
        return RedirectToAction("Index");
    } 

The model

 public partial class Publicacao
    {
        public int idpublicacao { get; set; }
        public string titulo { get; set; }
        public string texto { get; set; }
        public string imagem { get; set; }
        public System.DateTime data { get; set; }
        public int categoria { get; set; }
        public byte[] arqimagem { get; set; }
        public string descimagem { get; set; }
        public Nullable<int> usuario { get; set; }
        public int liberado { get; set; }
    
        public virtual categoria categoria1 { get; set; }
        public virtual Users Users { get; set; }
    }

CodePudding user response:

Have you tried debugging/place breakpoint in code? Did Find really returned something not null? Do you see publicacao.liberado equals 1 after publicacao.liberado = 1; line?

Also, didn't [ValidateAntiForgeryToken] returned html error and your code actually never run?

CodePudding user response:

I realised that I added 'liberado' in class but not in the edmx diagram. I could not add it mannualy to diagram, but used the Update Model from Database option and SaveChanges() is now working.

Thank you all.

  • Related