Why is EF Core updating data from other tables?

Asked

Viewed 186 times

2

Why EF Core is actuating data from other tables?

I am updating a table with EF but however I notice that EF is updating that table and still other tables.

 public async Task<IActionResult> Edit(int id, [Bind("Cor,Porte,Raca,Vacinado,Sexo,TipoAnimal,TipoAnuncio, Id,Descricao,Aprovado,DataPublicacao,Telefone,Email,Idade, Pais, Localidade")] Anuncio anuncio, IEnumerable<IFormFile> Imagens)
 {
    if (id != anuncio.Id)
    {
      return NotFound();
    }
            var anuncioActualizado = await _context.Anuncio.Include(x => x.Cor)
               .Include(x => x.Imagens)
               .Include(x => x.Localidade)
               .Include(x => x.Pais)
               .Include(x => x.Porte)
               .Include(x => x.Raca)
               .Include(x => x.Sexo)
               .Include(x => x.TipoAnimal)
               .Include(x => x.TipoAnuncio)
               .Include(x => x.User)
               .Include(x => x.Vacinado)
               .Include(x => x.Cor).Where(x => x.Id == id).FirstAsync();

            var userid = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            anuncioActualizado.Cor.Nome = _context.Cor.Where(x => x.Id == anuncio.Cor.Id).FirstOrDefault().Nome;
            anuncioActualizado.Porte.Nome = _context.Porte.Where(x => x.Id == anuncio.Porte.Id).FirstOrDefault().Nome;
            anuncioActualizado.Sexo.Nome = _context.Sexo.Where(x => x.Id == anuncio.Sexo.Id).FirstOrDefault().Nome;
            anuncioActualizado.TipoAnimal.Nome = _context.TipoAnimal.Where(x => x.Id == anuncio.TipoAnimal.Id).FirstOrDefault().Nome;
            anuncioActualizado.TipoAnuncio.Nome = _context.TipoAnuncio.Where(x => x.Id == anuncio.TipoAnuncio.Id).FirstOrDefault().Nome;
            anuncioActualizado.Vacinado.Nome = _context.Vacinado.Where(x => x.Id == anuncio.Vacinado.Id).FirstOrDefault().Nome;
            anuncioActualizado.Raca.Nome = _context.Raca.Where(x => x.Id == anuncio.Raca.Id).FirstOrDefault().Nome;
            anuncioActualizado.User = _context.Users.Where(x => x.Id == _userId).First();
            anuncioActualizado.Pais.Nome = _context.Pais.Where(x => x.Id == anuncio.Pais.Id).FirstOrDefault().Nome;
            anuncioActualizado.Localidade.Nome = _context.Localidade.Where(x => x.Id == anuncio.Localidade.Id).FirstOrDefault().Nome;
            anuncioActualizado.DataPublicacao = DateTime.Now;
            anuncioActualizado.Descricao = anuncio.Descricao;
            anuncioActualizado.Email = anuncio.Email;
            anuncioActualizado.Idade = anuncio.Idade;


            if (Imagens != null)
            await ActualizarImagemAsync(anuncioActualizado, Imagens);
            try
            {
                _context.Anuncio.Update(anuncioActualizado);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AnuncioExists(anuncio.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Anuncio", "Anuncios", new { id = anuncio.Id }); 
        }

So I just want to update the entity Anuncio However this is updating other entities like "Color", "Port" etc

 public class Anuncio: Animal
 {
        public int Id { get; set; }
        [Required]
        public string Descricao { get; set; }
        [Required]
        public TipoAnuncio TipoAnuncio { get; set; }
        [Required]
        public bool Aprovado { get; set; }
        [Required]
        public DateTime DataPublicacao { get; set; }
        [Required]
        public virtual ICollection<Imagem> Imagens { get; set; }
        [Required]
        public int Telefone { get; set; }
        [EmailAddress]
        public string Email { get; set; }
        [Required]
        public Pais Pais { get; set; }

        [Required]
        public Localidade Localidade { get; set; }

        public ApplicationUser User { get; set; }

 }

The other entities are all configured like this

public class Pais
{
   public int Id { get; set; }
   [Required]
   public string Nome { get; set; }
}
  • explain better!

  • When I try to update the entity Anuncio this updates the value of the entity Pais ie Country is a table where the data should not be changed but rather consumed but for some reason when I change Advertisement this changes the value of Country, imagine that I have 2 countries in Country Portugal, Brazil, suppose the Ad was created with Portugal and I switch to Brazil, what happens is that it changes in the Ad but also goes in the entity Country and puts where is Portugal = Brazil thus staying with two countries Brazil

  • Try to get the .Nome in all, example, anuncioActualizado.Cor = _context.Cor.Where(x => x.Id == anuncio.Cor.Id).FirstOrDefault();

1 answer

2


Amadeu, the values of the other tables are being changed because you are changing.

When you make this command: anuncioActualizado.Raca.Nome = _context.Raca.Where(x => x.Id == anuncio.Raca.Id).FirstOrDefault().Nome; the Entity makes the track of the entity Raca and believes that there has been a change to it.

I didn’t understand the need for you to have to set the name this way, but worrying only about not updating these entities, you can do the following

_context.Entry(anuncioActualizado.Raca).State == EntityState.Unchanged;

This will cause Entity to ignore entity changes Raca.

Another possibility is, the moment you are "changing" the name (as in this command anuncioActualizado.Raca.Nome = _context.Raca.Where(x => x.Id == anuncio.Raca.Id).FirstOrDefault().Nome;) you can stop the trackeation of the Entity:

_context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

Remember to return the Track for TrackAll:

_context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.TrackAll;

I hope I’ve helped.

  • 1

    Using Notracking... I don’t think it’s a good thing

  • Agree Renan, as it is something that refers to the context, any operation "cascade" can be affected. Have to be careful.

Browser other questions tagged

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