Error removing tuples from a table plus an intermediate one

I have 3 Tables, NOTICIA, NOTICIA_FOTO (Intermediate table) and FOTO, and I need to remove rows from Table FOTO; and since such table is associated with intermediate Table NOTICIA_FOTO, also remove rows from that table. What I'm trying to do, is delete multiple rows at once, using the Contains, where the Contains I pass a list of ids from FOTO to delete.

enter the description of the image here

I have the following code:

<HttpPost>
Function EditarNoticia(form As FormCollection) As ActionResult

Dim noticiaSelec As NOTICIA = db.NOTICIA.Where(Function(x) x.IdNoticia = id_noticia).Single()

 noticiaSelec.TituloNoticia = form("TituloNoticia")
 noticiaSelec.DescripcionNoticia = form("DescripcionNoticia")
 noticiaSelec.FechaPublicacionNoticia = Date.Now


 Dim idsEliminar() As Integer =   Array.ConvertAll(form("ids_eliminar").Split(","), Function(x) Int32.Parse(x))
Dim idsEliminarList As List(Of Integer) = idsEliminar.ToList

Dim fotosEliminar = db.FOTO.Where(Function(x)    idsEliminarList.Contains(x.IdFoto))        
noticiaSelec.FOTO.Remove(fotosEliminar) ‘ Aquí es donde se cae
db.SaveChanges()
……

But I get the next error:

Error name: cannot convert a type object 'System.Data.Entity.Infrastructure.DbQuery ' 1[IMPCHLosCopihues_MVC.PHOTO]' to type ' IMPCHLosCopihues_MVC.Photo'.

I know something wrong, and maybe the query fotosEliminar is wrong, but it throws me the error in noticiaSelec.FOTO.Remove(fotosEliminar). If anyone knows how to fix this error, I would appreciate it.

 2
Author: Carlos Muñoz, 2016-01-21

2 answers

Is that when using the Where() it returns a query when the Remove() needs a single item.

You should use FirstOrDefault():

Dim fotosEliminar = db.FOTO.FirstOrDefault(Function(x) idsEliminarList.Contains(x.IdFoto))

If fotosEliminar IsNot Nothing Then
   noticiaSelec.FOTO.Remove(fotosEliminar)
End If

If multiple records are required to be deleted then iterate for each one

Dim fotosEliminar = db.FOTO.Where(Function(x) idsEliminarList.Contains(x.IdFoto))

For Each item In fotosEliminar    
   noticiaSelec.FOTO.Remove(item) 
Next

db.SaveChanges()
 5
Author: Leandro Tuttini, 2016-01-21 17:02:47

When you want to remove multiple items at the same time, RemoveAll ()

Change the following code:

Dim fotosEliminar = db.FOTO.Where(Function(x) idsEliminarList.Contains(x.IdFoto))        
noticiaSelec.FOTO.Remove(fotosEliminar) ‘ Aquí es donde se cae

For something like this:

Dim fotosEliminar = db.FOTO.RemoveAll(Function(x) idsEliminarList.Contains(x.IdFoto)) 
 3
Author: fredyfx, 2016-01-21 19:11:04