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!
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With