使用ExecuteStoreCommand方法,代码如下.
using (var db = new msdbEntities())
{
db.ExecuteStoreCommand("DELETE " + db.students.EntitySet.ElementType.Name);
}
使用 Entity FrameWork 删除数据,着实是一件比较头疼的数据,若是少量数据,可以使用以下方法删除
var delete=db.NikeDTCDailyReport.Where(u => true);
foreach (var item in delete)
{
db.NikeDTCDailyReport.Remove(item);
}
db.SaveChanges();
给数据实体添加一个扩展方法,执行一个删除的SQL命令.如下:
public static class Extens
{
public static void DeleteAllSql(this ObjectContext ctx, string sql)
{
var entityConnection = (System.Data.EntityClient.EntityConnection)ctx.Connection;
DbConnection conn = entityConnection.StoreConnection;
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
finally
{
if (conn.State != ConnectionState.Open)
conn.Close();
}
}
}
使用方法如下:
using (var db = new msdbEntities())
{
db.DeleteAllSql("DELETE Students");
}