113408
113408

Reputation: 3444

Duplicate record in database when call SaveChanges()

Hi i have a problem with EF. In my application i have to load from database some content to populate a DataGrid.

UserControl :

 contenus = new List<Contenu>();
        contenus = sacoche.Contenus.ToList(); // i get sacoche in the parameter of the contructor
        ContenuViewSource.Source = contenus;
        ContenuView = (ListCollectionView)ContenuViewSource.View;
        ContenuView.Refresh();

everything work just fine, but when i try to add some others Contenus i get a duplicate record in the database. The only difference between the duplicated record is that the first record loose his foreign key.

Here i add my Contenuto my Sacoche:

editableSacoche = SacocheDal.dbContext.Sacoches.Include("Contenus").First(i => i.SacocheID == editableSacoche.SacocheID);
            editableSacoche.Contenus = contenus;
            SacocheDal.dbContext.SaveChanges();

all i do is get the Sacoche and add to it his Contenu and finally call SaveChanges().

Here is the result : problem duplicate

EDIT: I tried to get only the new items but failed.

List<Contenu> contenuAjoute = contenus.Except(editableSacoche.Contenus.ToList()).ToList();

in contenuAjoutei get all the records even if they are equal ...

Upvotes: 0

Views: 572

Answers (2)

113408
113408

Reputation: 3444

I found a way to achieve what i wanted. I create an ItemComparer and use Exceptto only add the new items.

Here is the comparer :

 class ContenuComparer : IEqualityComparer<Contenu>
{
    public bool Equals(Contenu x, Contenu y)
    {
        if (x.ContenuID == y.ContenuID)
            return true;

        return false;
    }

    public int GetHashCode(Contenu obj)
    {
        return obj.ContenuID.GetHashCode();
    }
}

And Here the code :

editableSacoche = SacocheDal.dbContext.Sacoches.Include("Contenus").First(i => i.SacocheID == editableSacoche.SacocheID);
            List<Contenu> contenuAjoute = contenus.Except(editableSacoche.Contenus.ToList(), new ContenuComparer()).ToList();
            foreach (Contenu c in contenuAjoute)
            {
                editableSacoche.Contenus.Add(c);
            }
            SacocheDal.dbContext.SaveChanges();

I don't now if it's the right way but it works fine.

Upvotes: 0

bobah75
bobah75

Reputation: 3560

Try this:

editableSacoche = SacocheDal.dbContext.Sacoches.Include("Contenus").First(i => i.SacocheID == editableSacoche.SacocheID);
editableSacoche.Contenus = null;
            editableSacoche.ContenusID = contenus.ID;
            SacocheDal.dbContext.SaveChanges();

Upvotes: 1

Related Questions