An image has many galleries, and a gallery has many images. I am trying to update the images that a gallery has. The code below works, but feels somewhat clumsy.
var g=db.Galleries.Find(gal.Id);
var ims = gal.Images.Select(i => db.Images.Where(im => im.Id == i.Id && im.User.Id == user.Id)).SelectMany(im => im).ToList();
g.Name = gal.Name;
g.Images.Clear();
foreach (var im in ims)
{
g.Images.Add(im);
}
db.SaveChanges();
When I do this:
g.Images=ims;
instead of:
g.Images.Clear();
foreach (var im in ims)
{
g.Images.Add(im);
}
An exception is thrown:
Violation of PRIMARY KEY constraint 'PK_GalleryImages'. Cannot insert duplicate key in object 'dbo.GalleryImages'.
Can you explain why? Is there a better way to approach this?
When you do
g.Images.Add(im), entity framework will add a new row withgalleryIdandimageIdindbo.GalleryImagestable if it doesn’t already exist in the table.On the otherhand, when you do
g.Images=ims, you are actually telling entity framework to add a new relation (new row in GalleryImages table). If you were to add new images into the galleryg.Images=imswould work fine.