简体   繁体   中英

'An entity object cannot be referenced by multiple instances of IEntityChangeTracker.' while deleting?

I tried to make a remove method of an object on a table of my database for a WPF project using C#, EF6 and XAML. I tried several different variation of it my last one. The error that VS throw me is the following one:

System.InvalidOperationException: 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker.'

Code:

private void btnSupprimer_Click(object sender, RoutedEventArgs e)
{
    var empASupprimer = ListViewEmployes.SelectedItems[0] as Employe;
    
    if (empASupprimer == null)
    {
        return;
    }
    else
    {
        using (var x = new ScriptBDEntity())
        {
            x.Employes.Attach(empASupprimer);
            x.Employes.Remove(empASupprimer);
                   
            x.SaveChanges();

            loadlistview();
            MessageBox.Show("Vous avez supprimer l'employé:" + empASupprimer);
        }
    }
}

Are you try to get employe by Id instead use attach ? Like

var employe = x.Employes.Single(e => e.Id == empASupprimer.Id),
X.Employes.Remove(employe);
X.SaveChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM