实体框架多对多更新

时间:2020-12-17 20:16:49

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?

你能解释一下为什么?有更好的方法来解决这个问题吗?

1 个解决方案

#1


1  

When you do g.Images.Add(im), entity framework will add a new row with galleryId and imageId in dbo.GalleryImages table if it doesn't already exist in the table.

当您执行g.Images.Add(im)时,实体框架将在dbo中添加一个带有galleryId和imageId的新行。如果表中不存在GalleryImages表的话。

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 gallery g.Images=ims would work fine.

另一方面,当你做g的时候。图像=ims,您实际上是在告诉实体框架添加一个新的关系(GalleryImages表中的新行)。如果你要添加新的图像到画廊g。图像= ims会更好。

#1


1  

When you do g.Images.Add(im), entity framework will add a new row with galleryId and imageId in dbo.GalleryImages table if it doesn't already exist in the table.

当您执行g.Images.Add(im)时,实体框架将在dbo中添加一个带有galleryId和imageId的新行。如果表中不存在GalleryImages表的话。

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 gallery g.Images=ims would work fine.

另一方面,当你做g的时候。图像=ims,您实际上是在告诉实体框架添加一个新的关系(GalleryImages表中的新行)。如果你要添加新的图像到画廊g。图像= ims会更好。