Delete From DataContext Using ID == ID with a simple LINQ query

c# entity-framework linq


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!

7/1/2011 6:23:37 PM

Accepted Answer

You currently have an IQueryable<Item>, not and Item - use Single() to get the item itself:

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

This assumes a single matching item (ID as primary key), otherwise consider using First() of FirstOrDefault() with a null check instead or if you have a collection of item, just delete them in a loop:

var items = DataContext.Items.Where(item => item.ItemId == selectedId);
foreach(var item in items)
7/1/2011 6:25:15 PM

Popular Answer

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

Don't forget to prevent error you'll need to ensure that the id you're checking on is of an actual Item. Something like this, for example:

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

if (item != null) {

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow