Configuration many to many code fast migration

2

Good afternoon!

I have this many-to-many configuration 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 work place, but when saving it creates a new work place in the working place table, with the same data of the referenced workplace, does anyone know how to solve it?

Thank you.

    
asked by anonymous 30.09.2017 / 17:37

1 answer

0

The Entity Framework at the time of user insertion does not track its ICollection<LocalAtendimento> LocalTrabalho property, because of this it believes that you want to insert new location, not just relate them.

Representation of what you are probably doing:

_contexto.Usuarios.Add(UsuarioQuePossuiColecaoPreenchida);

What you need is to 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 Entity will understand the SaveChages () call that is not to insert these values, but rather relate them.

    
03.10.2017 / 16:27