Error removing tuples from a table plus an intermediate

2

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

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 following error:

  

Error name: Unable to convert an object of type   'System.Data.Entity.Infrastructure.DbQuery'1 [IMPCHLosCopihues_MVC.FOTO]'   to the type 'IMPCHLosCopihues_MVC.FOTO'.

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

    
asked by Danilo 21.01.2016 в 14:59
source

2 answers

5

It is that by using the Where() this 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 it is required to delete several records then you have to 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()
    
answered by 21.01.2016 / 15:09
source
3

When you want to delete several items at the same time, RemoveAll () is used

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)) 
    
answered by 21.01.2016 в 20:07