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()
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.
You actually don’t need to loop to delete them.