Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple LINQ query to Delete From DataContext Where ID == ID

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!

like image 340
Jordan Foreman Avatar asked Jul 01 '11 18:07

Jordan Foreman


People also ask

How do I delete a record in LINQ query?

LINQ to SQL does not support or recognize cascade-delete operations. If you want to delete a row in a table that has constraints against it, you must complete either of the following tasks: Set the ON DELETE CASCADE rule in the foreign-key constraint in the database.

On which datasources do LINQ queries work?

In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, . NET collections, and any other format for which a LINQ provider is available.

Which of the following method is used to delete data from database using ADO Net?

You can use ExecuteNonQuery() for Inserting, Updating, and Deleting the data. So, basically ExecuteNonQuery() does, it returns the number of rows effecting when performing DML [Data Manipulation Language] operation into the database.

Which of the LINQ method is used to insert data into a relational table?

When using LINQ to SQL, you insert new records by calling the InsertOnSubmit() method. After calling the InsertOnSubmit() method, you must call SubmitChanges() to make the insertion happen.


1 Answers

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();
DataContext.Items.DeleteObject(item);

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)
  DataContext.Items.DeleteObject(item);
like image 183
BrokenGlass Avatar answered Oct 03 '22 17:10

BrokenGlass