简体   繁体   中英

Adding row to relational table - linq to sql

I have 3 primary Tables - Picture, Album and Collage . Collage and Album can have 1-many pictures. Pictures do not have to be in Album to be added to the Collage .

To define their relationship, I have AlbumPicture and CollagePicture tables.

My problem is when I try to add picture already uploaded to the Collage and hence to the CollagePicture table. It throws primry key violation error on PK_Picture since picture already exists.

CollagePictures.InsertOnSubmit(new CollagePicture {Collage = CollagePicture = existingPic});

I need to add one record in CollagePicture for existing picture and new Collage . Is there any way I can tell linq to not add picture if it already exists?

I am new to Linq and still learning.

EDIT: sorry If I was not clear. I assign PK to Picture as GUID when Pictures are uploaded. In CollagePicture I already have this pictureId with different collage

eg

CollagePictureId [PK]= 1
CollageId=1
PictureId = 1234567890123456

Now I want to add same Picture with different CollageId say,2. When I try to add anything to CollagePicture it tries to add to the Picture table as well. and that is when I get an exception. Hope this will clear things up.

I finally made it work..

Instead of this

CollagePictures.InsertOnSubmit(new CollagePicture {Collage = Collage, CollagePicture = existingPic});

It should be

CollagePictures.InsertOnSubmit(new CollagePicture {Collage = collage, CollagePicture.PictureId = existingPic.PictureId});

When you add an object to the relational table entity it adds the object in primary table as well. so just referencing Id makes sure that it does not do anything to the primary table.

It was easy and I should have tried that before..but Thanks for everyone's help though.

What primary key do you have on CollagePicture table? It's not really clear, what do you want to do when inserting new entry to CollagePicture. Do you mean that you add the existing picture to an existing collage? If so your primary key should be (PictureId, CollageId)

Without a detailed view of your data model, it's really hard to take a guess.

If you correctly configured your relations and LINQ to SQL, you could do something like the following:

collage.Add(Picture);

That way LINQ to SQL would add the right rows to the tables.

To check if the picure already exists in the Collage, you would do something like this.

collage.Pictures.Where(p => p.ID == pictureID).Count() > 0

If the PK of existingPic is 0 (assuming type int) then it is new, else it already exists.

if(existingPic.pkColumnId == 0)
  CollagePictures.InsertOnSubmit(existingPic);

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