A simple LINQ query to remove from a DataContext Where ID == ID

I get the identifier of the record in the database table in my code and try to find a simple LINQ query to delete the record based on the identifier.

Here is what I have:

DataContext.Items.DeleteObject((Item)DataContext.Items.Where(item => item.ItemId == selectedId)); 

This gives me a casting error, and I wonder if there is a better way to do this? I looked at similar questions, and every answer I see seems more complicated than it really should be, so any suggestions would be great!

+4
source share
2 answers

Currently you have IQueryable<Item> , not and Item - use Single() to get the element:

 var item = DataContext.Items.Where(item => item.ItemId == selectedId).Single(); DataContext.Items.DeleteObject(item); 

This assumes there is one matching element (identifier as primary key), otherwise use First() of FirstOrDefault() instead of null checking, or if you have a collection of elements, just delete them in a loop:

 var items = DataContext.Items.Where(item => item.ItemId == selectedId); foreach(var item in items) DataContext.Items.DeleteObject(item); 
+9
source
 DataContext.Items.DeleteObject((Item)DataContext.Items.Where(item => item.ItemId == selectedId).First()); 

Be sure to prevent the error to ensure that the identifier you are checking has the actual Item . Something like this, for example:

 var item = (Item)DataContext.Items.Where(item => item.ItemId == selectedId).FirstOrDefault(); if (item != null) { DataContext.Items.DeleteObject(item); } 
+2
source

All Articles