tags:

views:

64

answers:

1

Hi,

I'm starting my first Linq to SQL project in VB.NET (which I am also new to). I am trying to Delete an entity but am having trouble with an InvalidCastException. The debugger breaks at the Next statement in the ForEach loop.

My entity class is called Material.

Any help would be very much appreciated.

Thanks,

Kenneth

        Dim materialsTable As Table(Of Material) _
                 = (New DataContext("Server=.\SQLEXPRESS; Database=Materials; Trusted_Connection=yes;") _
                    .GetTable(Of Material)())

        Dim materialsToDelete = (From x In materialsTable _
                                 Where x.MaterialName = aMaterial.MaterialName _
                                 Select x)

        If (materialsToDelete Is Nothing) Then Return
        If (materialsToDelete.Count = 0) Then Return

        For Each m As Material In materialsToDelete
            materialsTable.DeleteOnSubmit(m)
        Next

        materialsTable.Context.SubmitChanges()
+1  A: 

Make sure you actually run the query with a .ToList()

Also, go with a straightforward DataContext if you can. I've not seen your implementation of the DC anywhere.

 Dim db as new NorthwindDataContext()
 Dim materialsToDelete = (From x In db.Materials _
                             Where x.MaterialName = aMaterial.MaterialName _
                             Select x)

You actually don't need to loop to delete them.

materialsTable.DeleteAllOnSubmit(materialsToDelete)
materialsTable.Context.SubmitChanges()
p.campbell
Thanks for the help. Using .ToList() results in an InvalidCastException on that line..
KennethC
@KennethC: how about explicitly declaring the type of materialsToDelete? Also, go with a new DataContext object, rather than your current approach.
p.campbell
Ended up reverting back the the VS designer and the generated context works fine.
KennethC