Update Many to Many relationship EF code first RRS feed

  • Question

  • Hi,

    this is my model schema

    public class Local
            [HiddenInput(DisplayValue = false)]
            public int IdEstablecimiento { get; set; }
            [Required(ErrorMessage = "Nombre requerido")]
            public string Nombre { get; set; }
            public DateTime? HoraApertura { get; set; }
            public virtual ICollection<Musica> TiposMusica { get; set; }
    public class Musica
            [HiddenInput(DisplayValue = false)]
            public int IdTipoMusica { get; set; }
            [Required(ErrorMessage="Tipo de música requerido")]
            [DisplayName("Tipo de música")]
            public string Nombre { get; set; }
            public virtual ICollection<Local> Locales { get; set; }


                .HasMany(e => e.TiposMusica)
                .WithMany(e => e.Locales)
                .Map(m =>

    The problem cames when I tried to Update a Local with a collection of Music. If Local object doesn´t have Music collection I´m able to update it correctly.

    I´m using Generic repository, this is the update method.

    public virtual void Update(T entity)
                var entry = _dbContext.Entry(entity);
                entry.State = EntityState.Modified;

    this is the error message:

    "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."

    dbContext is shared by all repositories (injected).

    Thank you in advance.

    Visita mí BlOg y Colabora con tus comentarios ;-) Gracias.

    Thursday, October 11, 2012 12:37 PM


  • Hi Jorge,

    Welcome to the MSDN forum.

    If I understand correctly, your code attach the entity object repeatedly. I am not sure if what you want is update an existing entity with the parameter entity. Please check this:

    If you want to add a TiposMusica object to local object, you need pass a two parameters (since the association is many to many): which object new one should add into, and new one. Then you can add the new entity object into a collection of a specific existing entity object.

    Best Regards,

    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by Alexander Sun Tuesday, October 23, 2012 8:43 AM
    Monday, October 15, 2012 6:04 AM