Update to 2 tables

Asked

Viewed 185 times

2

I cannot update the 2 tables. The problem is here.

  db.Entry(catequizando).State = EntityState.Modified;
  db.Entry(pessoa).State = EntityState.Modified;
  db.SaveChanges();

Some solution?

Controller:

  [HttpPost]
  [ValidateAntiForgeryToken]
     public ActionResult Edit(CatequizandoCreateModel CatequizandoModel)
    {
        if (ModelState.IsValid)
        {
            //criar um novo objeto para o model pessoa
            var pessoa = new Pessoa
            {
                Nome = CatequizandoModel.pessoa.Nome,
                Morada = CatequizandoModel.pessoa.Morada,
                Localidade = CatequizandoModel.pessoa.Localidade,
                CodPostal = CatequizandoModel.pessoa.CodPostal,
                Telemovel = CatequizandoModel.pessoa.Telemovel,
                Email = CatequizandoModel.pessoa.Email,
                Genero = CatequizandoModel.pessoa.Genero,
                Naturalidade = CatequizandoModel.pessoa.Naturalidade,
                Nacionalidade = CatequizandoModel.pessoa.Naturalidade,
                BI = CatequizandoModel.pessoa.BI,
                NIF = CatequizandoModel.pessoa.NIF,
                Estado_Civil = CatequizandoModel.pessoa.Estado_Civil,
                Profissao = CatequizandoModel.pessoa.Profissao,
                Habilitacoes_Literarias = CatequizandoModel.pessoa.Habilitacoes_Literarias,
                DataNascimento = CatequizandoModel.pessoa.DataNascimento,
                Foto = CatequizandoModel.pessoa.Foto,
                Observacoes = CatequizandoModel.pessoa.Observacoes
            };
            //   criar um novo objeto para o model Catequizando
            var catequizando = new Catequizando
            {
                NomeEscola = CatequizandoModel.catequizando.NomeEscola,
                AnoEscolar = CatequizandoModel.catequizando.AnoEscolar,
                TurmaEscolar = CatequizandoModel.catequizando.TurmaEscolar,
                CedulaCrista = CatequizandoModel.catequizando.CedulaCrista,
            };
            db.Entry(catequizando).State = EntityState.Modified;
            db.Entry(pessoa).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.CatequizandoID = new SelectList(db.Pessoa, "PessoaID", "Nome", CatequizandoModel.CatequizandoID);
        return View(CatequizandoModel);
    }
  • What problem are you having?

  • "Store update, Insert, or delete statement affected an Unexpected number of Rows (0). Entities may have been modified or Deleted Since entities Were Loaded."

3 answers

3

If you’re creating a new Pessoa and new Catequizando you can never make a EntityState.Modified;, because basically the items don’t exist.

Or the element you’re instantiating has a id existing, where you have to put the id from CatequizandoModel:

var pessoa = new Pessoa
{
  id = CatequizandoModel.Pessoa.Id
  ...
}

var pessoa = new Catequizando
{
  id = CatequizandoModel.Catequizando.Id
  ...
}

Or just save the received Model data:

db.Entry(CatequizandoModel.catequizando).State = EntityState.Modified;
db.Entry(CatequizandoModel.pessoa).State = EntityState.Modified;
  • I opted for the last solution and error in db.SaveChanges();

  • and what mistake is it? You can say

3


The approach is incorrect. This error you are experiencing:

"Store update, Insert, or delete statement affected an Unexpected number of Rows (0). Entities may have been modified or Deleted Since entities Were Loaded."

It is when the primary key is not set. In fact you should have brought the database records and changed them. Have not created new ones:

    if (ModelState.IsValid)
    {
        var pessoa = db.Pessoas.SingleOrDefault(p => p.PessoaId == CatequizandoModel.Pessoa.PessoaId);
        var catequizando = db.Catequizandos.SingleOrDefault(p => p.CatequizandoId == CatequizandoModel.Catequizando.CatequizandoId);

            pessoa.Nome = CatequizandoModel.pessoa.Nome;
            pessoa.Morada = CatequizandoModel.pessoa.Morada;
            pessoa.Localidade = CatequizandoModel.pessoa.Localidade;
            pessoa.CodPostal = CatequizandoModel.pessoa.CodPostal;
            pessoa.Telemovel = CatequizandoModel.pessoa.Telemovel;
            pessoa.Email = CatequizandoModel.pessoa.Email;
            pessoa.Genero = CatequizandoModel.pessoa.Genero;
            pessoa.Naturalidade = CatequizandoModel.pessoa.Naturalidade;
            pessoa.Nacionalidade = CatequizandoModel.pessoa.Nacionalidade;
            pessoa.BI = CatequizandoModel.pessoa.BI;
            pessoa.NIF = CatequizandoModel.pessoa.NIF;
            pessoa.Estado_Civil = CatequizandoModel.pessoa.Estado_Civil;
            pessoa.Profissao = CatequizandoModel.pessoa.Profissao;
            pessoa.Habilitacoes_Literarias = CatequizandoModel.pessoa.Habilitacoes_Literarias;
            pessoa.DataNascimento = CatequizandoModel.pessoa.DataNascimento;
            pessoa.Foto = CatequizandoModel.pessoa.Foto;
            pessoa.Observacoes = CatequizandoModel.pessoa.Observacoes;


            catequizando.NomeEscola = CatequizandoModel.catequizando.NomeEscola;
            catequizando.AnoEscolar = CatequizandoModel.catequizando.AnoEscolar;
            catequizando.TurmaEscolar = CatequizandoModel.catequizando.TurmaEscolar;
            catequizando.CedulaCrista = CatequizandoModel.catequizando.CedulaCrista;
        db.Entry(catequizando).State = EntityState.Modified;
        db.Entry(pessoa).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
  • That’s basically it, +1. But it was avoided that he had to do all these equalities, right?

  • pessoa.Nome is null and the error is: "Object Reference not set to an instance of an Object.".

  • @user10271 There you have to check if the Ids are coming from the screen. From what you said, are not.

  • To PessoaID and CatequizandoID is always at 0.

  • @user10271 So. As I told you, you need to write these Ids on View. MVC has no way of guessing which record you are editing.

  • Of course. @Html.HiddenFor(model => model.catequizando.CatequizandoID)
 @Html.HiddenFor(model => model.pessoa.PessoaID)

Show 1 more comment

1

If you don’t need to get the data in the database before making the change, you can perform Attach before you make Savechanges, in some cases this is very good to avoid I/O’s.

//código que cria pessoa e catequizando.....

db.Pessoas.Attach(pessoa);
db.CatequizandosAttach(catequizando);
db.Entry(pessoa).State = EntityState.Modified;
db.Entry(catequizando).State = EntityState.Modified;

db.SaveChanges();
  • I haven’t quite figured out how Attach.

  • @user10271 Attach is used to indicate to context that the object has already been loaded somewhere else, but I particularly consider this approach dangerous because you have no way of verifying for it whether or not the record exists in bank.

  • Attach is for you to link an object instance in the context. In this scenario that he pointed out above instead of going into the database to take the person via Single and change the fields, if he has the values of the object’s key he can simply create an instance of the object by passing the key (ID field for example) "attachar" this new instance in the context inform the context that this instance has changed and give a Savechanges. EF will understand that the fields of a record previously registered in the database has been changed and will perform the update.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.