invalidOperationException: Cannot attach an entity that already exists

Last post 07-07-2009 12:16 PM by onetae. 9 replies.

Sort Posts:

  • invalidOperationException: Cannot attach an entity that already exists

    04-13-2009, 5:31 PM
    • Member
      7 point Member
    • attawba
    • Member since 04-05-2009, 11:17 AM
    • Posts 83

    that's my code (data access layer, im using linq to sql)

     

     public class ClientDAO : IClient
        {
            private static DataClassesDataContext db;
            
           
            #region Constructeur
    
            public ClientDAO()
            {
                try
                {
                    ConnectionStringSettings settings;
                    settings = ConfigurationManager.ConnectionStrings["Gestion_flotteConnectionString1"];
                    db = new DataClassesDataContext(settings.ConnectionString);
                }
                catch (NullReferenceException) { }
            }
            #endregion
    
            #region CRUD
           
    
            public bool ModifierClient(client oClient)
            {
    
    
                ChangeSet changeset = null;
                int changeCount = 0;
                
                    db.client.Attach(oClient);
    
                    changeset = db.GetChangeSet();
    
                    changeCount = changeset.Updates.Count;
    
                    db.SubmitChanges();
    
                
                if (changeCount > 0) { return true; }
    
                else { return false; }
            }
     :

     and my business class :

     

    public class Clientbusiness : IClientbusiness
        {
           #region Données privées de la classe
            private IClient _iClient;
            #endregion
    
            #region Constructeur
            public Clientbusiness()
            {
                _iClient = new ClientDAO();
            }
    
            #endregion
    
            #region Getter and Setter
            public IClient IClient
            {
                get { return this._iClient; }
                set { this._iClient = value; }
            }
            #endregion
    
            #region Methode Business
            
            #region Operation CRUD
           
            public bool ModifierClient(client oClient)
            {
                return _iClient.ModifierClient(oClient);
            }

      and finally my code behind *.aspx.cs

     

     protected void charger()
        {
            oEntreprise = (entities.entreprise) HttpContext.Current.Session[IDvariable];
            oClient = iclientbusiness.GetClientByIdClient(oEntreprise.id_client);
            Textloginclient.Text = oClient.login_client;
            Textnomclient.Text = oClient.nom_client;
            Textprenomclient.Text = oClient.prenom_client;
            Textpswdclient.Text = oClient.pswd_client.ToString(); ;
            Textemailclient.Text = oClient.email_client;
            Texttelclient.Text = oClient.tel_client.ToString();
            Textadresseentreprise0.Text = oEntreprise.adresse_entreprise;
            Texttelentreprise.Text = oEntreprise.telephone_entreprise.ToString();
            Textnomentreprise.Text = oEntreprise.nom_entreprise;
        }
        protected void enregister()
        {
            oClient.nom_client = Textnomclient.Text;
            oClient.prenom_client = Textprenomclient.Text;
            oClient.pswd_client = FormsAuthentication.HashPasswordForStoringInConfigFile(Textpswdclient.Text,"MD5");
            oClient.email_client = Textemailclient.Text;
            oClient.tel_client = int.Parse(Texttelclient.Text);
            oClient.login_client = Textloginclient.Text;
            oEntreprise.telephone_entreprise = ientreprisebbusiness.GetEntrepriseByIdClient(oClient.id_client).telephone_entreprise;
            oEntreprise.nom_entreprise = ientreprisebbusiness.GetEntrepriseByIdClient(oClient.id_client).nom_entreprise;
            oEntreprise.adresse_entreprise = ientreprisebbusiness.GetEntrepriseByIdClient(oClient.id_client).adresse_entreprise;
            oEntreprise.nom_entreprise = Textnomentreprise.Text;
            oEntreprise.adresse_entreprise = Textadresseentreprise0.Text;
            oEntreprise.telephone_entreprise = int.Parse(Texttelentreprise.Text);
            iclientbusiness.ModifierClient(oClient);
            ientreprisebbusiness.ModifierEntreprise(oEntreprise);
            
    
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            this.enregister();
            Response.Redirect("loginadministrateur.aspx",false);
        }

      i have problem with  the method "enregister" in aspx.cs, when i start  the debug , i got this exception :"invalidOperationException:  Cannot attach an entity that already exists" in    the class ClientDAO : ( i dont understand why as i try to update this entity)

    any ideas??

    thanks 

  • Re: invalidOperationException: Cannot attach an entity that already exists

    04-13-2009, 7:29 PM
    Answer
    • Contributor
      5,076 point Contributor
    • Paul Linton
    • Member since 04-30-2008, 3:16 AM
    • Posts 883

    I assume that somehow charger is called before enregister is called which sets the global(?) variable called oClient.  From the method name, GetClientByIdClient, I also guess that you are retrieving oClient from the database.  If these things are true (and the error message you quote implies this) then you should not Attach this client back to the database as it is already attached. 

    The fix should be easy, remove the line from ClientDAO.ModifierClient which does the attach.

    Got a c# problem? Try .NET Book Zero from Charles Petzold, it's a free pdf.
  • Re: invalidOperationException: Cannot attach an entity that already exists

    04-14-2009, 4:49 AM
    • Member
      7 point Member
    • attawba
    • Member since 04-05-2009, 11:17 AM
    • Posts 83

     hi, you're right, but how can  I update (edit) the entity oClient  if I  remove the line which does the attach in clientDao.modifierclient?

    because; i think , ill need a methode that assure the update of this entity??

  • Re: invalidOperationException: Cannot attach an entity that already exists

    04-14-2009, 7:38 AM
    • Member
      171 point Member
    • SMHoff
    • Member since 01-08-2009, 12:54 PM
    • Mendota Heights, Minnesota
    • Posts 27

    I'm just curious what would happen if you made your datacontext an instance member rather than static? The datacontext is not meant to be a long lived object and I am guessing that by having it static, the change tracking is getting screwy when you are attaching and detaching.

     Take a peek at this link: LINQ to SQL ObjectTrackingEnabled and Deferred Loading of Related Data

  • Re: invalidOperationException: Cannot attach an entity that already exists

    04-14-2009, 8:10 AM
    • Member
      7 point Member
    • attawba
    • Member since 04-05-2009, 11:17 AM
    • Posts 83

      i change the instance of datacontext, (i removed static) ,

    but i still have this error  when i start the debug :

    An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy ??

    any ideas , ?????

     

     

  • Re: invalidOperationException: Cannot attach an entity that already exists

    04-14-2009, 5:49 PM
    • Member
      171 point Member
    • SMHoff
    • Member since 01-08-2009, 12:54 PM
    • Mendota Heights, Minnesota
    • Posts 27

    Well, I'm guessing that you do not have a timestamp column in your table?

     The solution to this is, as silly as it may seem, to add a timestamp in Sql to the table.

    This link should explain it in detail:

    http://geekswithblogs.net/michelotti/archive/2007/12/17/117791.aspx

  • Re: invalidOperationException: Cannot attach an entity that already exists

    04-14-2009, 6:13 PM
    • Member
      7 point Member
    • attawba
    • Member since 04-05-2009, 11:17 AM
    • Posts 83

     

    ive tried timestamp, but i have tables which are associated  to this table,

    si it doesn't work, i got an  article which talk about tthat, and even if we add a timestamp in the other tables , it doesn't resolve the problem!!

    :(

    thanks 

  • Re: invalidOperationException: Cannot attach an entity that already exists

    04-14-2009, 6:58 PM
    • Contributor
      5,076 point Contributor
    • Paul Linton
    • Member since 04-30-2008, 3:16 AM
    • Posts 883

    Have you removed the Attach?  LinqToSql will keep track of the changes to your objects.

    Got a c# problem? Try .NET Book Zero from Charles Petzold, it's a free pdf.
  • Re: invalidOperationException: Cannot attach an entity that already exists

    04-15-2009, 5:58 AM
    • Member
      7 point Member
    • attawba
    • Member since 04-05-2009, 11:17 AM
    • Posts 83

     i tried it but the update doesnt work!!!

  • Re: invalidOperationException: Cannot attach an entity that already exists

    07-07-2009, 12:16 PM
    • Member
      4 point Member
    • onetae
    • Member since 06-25-2009, 3:53 AM
    • Posts 2

     The only way to get around this problem is to create a new DataContext just before you do the Attach and not use a global DataContext.

    I haven't found any other way, I would rather use a global context but it causes too many problems like this.

Page 1 of 1 (10 items)