I am getting the ID of an entry in a database table in my codebehind, and am trying to find a simple LINQ query to delete the entry based on the ID.
Here is what I have:
DataContext.Items.DeleteObject((Item)DataContext.Items.Where(item => item.ItemId == selectedId));
This gives me a casting error however, and I am wondering if there is a better way to accomplish this? I’ve looked at similar questions and every answer I see seems to be more complicated than this should actually be, so any suggestions would be great!
You currently have an
IQueryable<Item>, not and Item – useSingle()to get the item itself:This assumes a single matching item (ID as primary key), otherwise consider using
First()ofFirstOrDefault()with a null check instead or if you have a collection of item, just delete them in a loop: