Reputation: 8761
Is there a built in way to delete with Linq to Entites, using the Primary Key.
Currently m work around is to create a Stored Procedure called DeleteTable (table being the table name)
and then in C# LINQ To Entities I just do context.DeleteTable(ID)
Is this the best way? What other options are there?
Upvotes: 12
Views: 13886
Reputation: 471
I use to search the item(s) to delete and then delete it(them) using DeleteObject method.
Dim itemToDelete = (From u In db.SOME_TABLE Where u.ID = ID).FirstOrDefault
db.SOME_TABLE.DeleteObject(itemToDelete)
db.SaveChanges()
use this inside a try catch block
Upvotes: 2
Reputation:
If you don't want to go to the database to retrieve all of the object's fields, you can create a new instance of the class, attach it to a new context, remove that, and save the changes. This lets EF generate the appropriate delete command.
using (var context = new MyContext())
{
var myObject = new MyObject { ID = 3 };
context.MyObjectSet.Attach(myObject);
context.MyObjectSet.DeleteObject(myObject);
context.SaveChanges();
}
Note: this will throw an exception of you're trying to delete an object which does not exist. That's only appropriate if you're sure the object exists.
Note 2: this assumes you've set up your entities so that the generated delete command references no other fields than the ID (meaning no Timestamp properties, or anything similar that would be included in the query)
Upvotes: 12
Reputation: 16038
You can use the DbSet<T>.Remove(entity)
(Version 4.1, 4.2) or EntitySet<T>.Remove(entity)
(Version 1.0, 4.0) methods:
YourDbContext.Table.Remove(entityObject);
Upvotes: 2
Reputation: 31721
Use the execute command to your needs off of the context such as:
mycontext.ExecuteCommand("DELETE FROM MYTABLE");
or
mycontext.ExecuteCommand("TRUNCATE TABLE MYTABLE");
HTH
Upvotes: 1
Reputation: 22443
The default way would be to query out the entity and then issue the .DeleteObject(...) method.
Upvotes: 5