System.InvalidOperationException: Cannot attach an entity that already exists

I am trying to connect to an object from which I was previously separated. My disconnect operation is as follows:

partial class Organization : IDetachable
{
    #region IDetachable Members
    public void Detach()
    {
        if (IsAttached)
        {
            PropertyChanged = null;
            PropertyChanging = null;

            // Detach children -- administrators first.
            foreach (var administrator in Administrators)
            {
                // Detach all of our administrators.
                if (administrator.IsAttached)
                {
                    administrator.Detach();
                }
            }

            // now detach users.
            foreach (var user in Users)
            {
                if (user.IsAttached)
                {
                    user.Detach();
                }
            }
        }
    }
    #endregion
}

Note that there are two children for this type: Organization: Administrators and Users. When I download the Organization, I disconnect from all of them.

In my scenario, I am trying to create a new administrator. Here is the code from my AdministratorRepository:

public void Save(Administrator administrator)
{
    if (!DataContext.Administrators.Contains(administrator))
    {
        Log.Debug("This is a new administrator.");
        administrator.Id = Guid.NewGuid();
        administrator.CreatedDate = DateTime.Now;
        administrator.Disabled = false;

        DataContext.Organizations.Attach(administrator.Organization);
        DataContext.Administrators.InsertOnSubmit(administrator);
    }
    else
    {
        // Attach to our data context.
        DataContext.Administrators.Attach(administrator);
    }

    DataContext.SubmitChanges();

    // Now that we're done...
    administrator.Detach();
}

I am currently getting an exception when trying to connect to an organization (DataContext.Organizations.Attach (administrator.Organization)). I checked that

  • Organization is valid and disabled (i.e., event handlers are null)
  • In the list of administrators (the administrator I'm trying to save now) there is only one administrator.

, , - - (.. ID , ), ?

, → LINQ to SQL?

+3
1

, ? , :

if (!DataContext.Organizations.Contains(administrator.Organization))
{
   DataContext.Organizations.Attach(administrator.Organization);
}
+1

Source: https://habr.com/ru/post/1741868/


All Articles