Settings Many to Many code fast Migration

Asked

Viewed 31 times

2

good afternoon!

I have this many configuration for many in my project.

public class Usuario
{
    public Usuario()
    {
        this.LocalTrabalho = new HashSet<LocalAtendimento>();
    }
    public virtual ICollection<LocalAtendimento> LocalTrabalho { get; set; }
}

public class LocalTrabalho 
{
    public LocalTrabalho ()
    {
        this.Usuarios = new HashSet<Usuario>();
    }
    public virtual ICollection<Usuario> Usuarios{ get; set; }
}


modelBuilder.Entity<LocalAtendimento>()
            .HasMany<Usuario>(s => s.Usuarios)
               .WithMany(c => c.LocalTrabalho)
               .Map(cs =>
               {
                   cs.MapLeftKey("LocalTrabalho_Seq");
                   cs.MapRightKey("Usuario_Seq");
                   cs.ToTable("LocalTrabalhoUsuario");
               });

When I save a user it should only reference the workplace, but when saving it creates a new workplace in the workplace table, with the same data of the referenced workplace, someone knows how to solve?

Thank you.

  • Enter the code that makes the register.

1 answer

0

Entity Framework at the time of User insertion has no tracking of its property ICollection<LocalAtendimento> LocalTrabalho, because of this he believes that you want to insert new localAtendimento, and not just relate them.

Representation of what you are probably doing:

_contexto.Usuarios.Add(UsuarioQuePossuiColecaoPreenchida);

What you need to do is Attach these properties before calling Savechanges():

foreach(var local in UsuarioQuePossuiColecaoPreenchida.LocalTrabalho)
{
    _contexto.LocaisAtendimento.Attach(local);
    //A linha abaixo terá o mesmo efeito. Escolha uma.
    //_contexto.Entry(local ).State = EntityState.Unchanged; 
}
_contexto.Usuarios.Add(UsuarioQuePossuiColecaoPreenchida);

When you do an Attach(), you are tracking your object again in the Unchanged state, that is, it will not change its value and the Entity will understand in the Savechages() call that it is not to enter these values, but relate them.

Browser other questions tagged

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