Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8947563
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T12:47:44+00:00 2026-06-15T12:47:44+00:00

I have an ASP.NET WebForms project with N-Layers using Entity Framework 5. I have

  • 0

I have an ASP.NET WebForms project with N-Layers using Entity Framework 5.
I have two entities: Cliente and Banda.
One Cliente may have many Banda’s, and one Banda may have many Cliente’s

In the bussines layer I have this code:

public void Update(Cliente cliente)
    {
        using (MegaStudioEntities contexto = new MegaStudioEntities())
        {
            if (contexto.Entry(cliente).State == EntityState.Detached)
                contexto.Entry(cliente).State = EntityState.Modified;

            //Delete existing relations
            var qBandas = from qb in contexto.Bandas.Where(b => b.Clientes.Any(c => c.IdCliente == cliente.IdCliente))
                          select qb;


            foreach (Banda b in qBandas.ToList())
                ((IObjectContextAdapter)contexto).ObjectContext.ObjectStateManager.ChangeRelationshipState(cliente, b, c => c.Bandas, EntityState.Deleted);

            contexto.SaveChanges();

            //Adding new relations
            foreach (Banda banda in cliente.Bandas)
            {
                contexto.Bandas.Attach(banda);
                ((IObjectContextAdapter)contexto).ObjectContext.ObjectStateManager.ChangeRelationshipState(cliente, banda, c => c.Bandas, EntityState.Added);
            }

            cliente.TipoCliente = contexto.TipoClientes.Find(cliente.IdTipoCliente);
            cliente.FechaModificacion = System.DateTime.Now;
            Encriptar(cliente);
            contexto.SaveChanges();
        }
    }

The first time I call Update method, run sucessfully, but the second time I get this error:

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

What I forget to close?
This is the correct way to update many to many relations in EF5?

Thanks in advance!!!

Martin

UPDATE 1:

Finally my code is like that:

public void Update(Cliente cliente)
        {
            using (MegaStudioEntities contexto = new MegaStudioEntities())
            {
                Cliente savedClient = contexto.Clientes.Find(cliente.IdCliente);

                foreach (var banda in savedClient.Bandas.ToList())
                {
                    savedClient.Bandas.Remove(contexto.Bandas.Find(banda.IdBanda));
                }

                foreach (var banda in cliente.Bandas)
                {
                    savedClient.Bandas.Add(contexto.Bandas.Find(banda.IdBanda));
                }

                contexto.Entry(savedClient).CurrentValues.SetValues(cliente);
                contexto.SaveChanges();
            }
        }

Thanks Gert Arnold!!!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T12:47:46+00:00Added an answer on June 15, 2026 at 12:47 pm

    You don’t really have to attach any object to the context. So you can prevent this exception by not doing that.

    public void Update(Cliente cliente)
    {
        using (MegaStudioEntities contexto = new MegaStudioEntities())
        {
            Cliente savedClient = contexto.TipoClientes.Find(cliente.IdCliente);
    
            foreach (var banda in savedClient.Bandas.ToList())
            {
                savedClient.Bandas.Remove(banda);
            }
            foreach (var banda in cliente.Bandas)
            {
                savedClient.Bandas.Add(banda);
            }
    
            savedClient.IdTipoCliente = cliente.IdTipoCliente;
            savedClient.FechaModificacion = System.DateTime.Now;
    
            Encriptar(cliente);
            contexto.SaveChanges();
        }
    }
    

    I’m not sure if this break code in Encriptar(cliente); because (obviously) I don’t know what happens there.

    As you see, you add and remove associations in a m:m relationship by adding/removing objects. You hardly ever (probably never) need to manipulate relationship state explicitly. If you feel a need to do that it most likely indicates that you overlook an easier way to achieve what you want.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

My project is in Asp.Net Webforms using C#. On one of my web pages,
My project is ASP.Net WebForms on 4.0 framework, using the ReportViewer 10, local RDLC
I have a hybrid ASP.NET WebForms/MVC project. In my Master Page, I have a
I have an ASP.NET project (VS2008 on Windows 7 with either webforms, MVC1, or
I have a asp.net webforms page in which I'm using the jqGrid component. The
When using ASP.net webforms my usual solution would have following type of setup -
I have an ASP.NET 3.5 webforms project written in VB that involves a multi-table
I have ASP.NET WebForms project with online player. When i click play player asks
I have asp.net 4 webforms website which references PortableLibrary project. In the website I
I have a asp.net webforms 3.5 solution with multiple projects. In one of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.