Reputation: 2629
I tries to delete an entity - table
This is the code:
db.Sessions.SqlQuery("delete table session");
db.SaveChanges();
This isnt delete the table. Or do anything.. db is inherits from DbContext object.
I've found a solution
foreach (var item in db.Sessions)
{
db.Sessions.Remove(item);
}
db.SaveChanges();
But I'm sure theres a better way.
Thanks.
Upvotes: 1
Views: 1549
Reputation: 139758
SqlQuery
as the name implies only for executing queries if you want to drop the table you need something else:
With the use of the DbContext.Database property you can execute any DDL/DML query:
db.DataBase.ExecuteSqlCommand("drop table sessions");
I have also created a repro and it's working fine with EF4.3.1 with SQL Server2008:
using (var db = new EFRepros())
{
db.Sessions.Add(new Session() { Name = "Test1" });
db.Sessions.Add(new Session() { Name = "Test2" });
db.Sessions.Add(new Session() { Name = "Test3" });
db.SaveChanges();
Console.WriteLine(db.Sessions.Count()); // Output: 3
db.Database.ExecuteSqlCommand("delete from sessions");
//db.Database.ExecuteSqlCommand("truncate table sessions"); //this also works
Console.WriteLine(db.Sessions.Count()); // Output: 0
}
Note: EF by default use plurar table names so you need to use sessions.
Upvotes: 2
Reputation: 13549
Are you trying to drop the table? If so, you can't do that through a SqlQuery
call because, as the name implies, that method deals strictly with querying.
If you're trying to delete all the rows from a table, then this question is a duplicate of this:
Linq to Sql: How to quickly clear a table
Upvotes: 1