文章内容

2017/3/28 8:58:20,作 者: 黄兵

Entity Framework 4中删除所有数据行的几种方法

有朋友问如何删除所有数据行的方法.的确,EF目前没有提供删除所有数据行的方法.所以下面给大家介绍几种方法.

 

方法1:

使用ExecuteStoreCommand方法,代码如下.

using (var db = new msdbEntities())

{

     db.ExecuteStoreCommand("DELETE " + db.students.EntitySet.ElementType.Name);

}

因为xx. EntitySet.ElementType.Name就是对应的数据表名称,所以可以使用delete 拼接数据表名来删除数据.

 

方法2:

在数据实体中添加一个删除所有对象的方法.如下:

    public partial class msdbEntities : ObjectContext

    {

 

       //其他代码

       //…..

      

        public void DeleteObjects(IEnumerable entities)

        {

            foreach (var entity in entities)

            {

                this.DeleteObject(entity);

            }

        }

 

    }

 

使用代码如下:

 using (var db = new msdbEntities())

 {

      db.DeleteObjects(db.students.Where(c => c.Id == c.Id));

      db.SaveChanges();

 }

 

方法3:

给数据实体添加一个扩展方法,执行一个删除的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");

   }

 

 

总结下来,目前没有提供删除所有数据对象的方法,所以一般需要自己添加方法或者添加扩展方法来实现.



1、使用 Entity FrameWork  删除数据,着实是一件比较头疼的数据,若是少量数据,可以使用以下方法删除


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 public ActionResult DeleteProject(int Id, string Project)
        {
            switch (Project)
            {
                case "First":
                    using(UnitOfWork uow=new UnitOfWork())
                    {
                        //二级目录无一级目录Id,则直接删除
                        //如果二级目录有一级目录Id,先删除二级目录,之后再删除一级目录
                        var getFirst = uow.SecondProjectRepository.GetAll().Where(x =>x.FirstProId  == Id);
                        if (getFirst.Count() == 0)
                        {
                            var getFirstItem = uow.FirstProjectRepository.Get(x => x.Id == Id);
                            uow.FirstProjectRepository.Delete(getFirstItem);
                            uow.SaveChanges();
                        }
                        else
                        {
                            //二级目录可能有多个一级目录ID,这里是多数据删除
                            foreach( var item in uow.SecondProjectRepository.GetAll().Where(x => x.FirstProId == Id))
                            {
                                uow.SecondProjectRepository.Delete(item);
                                uow.SaveChanges();
                            }
                            //二级目录删除完成后,删除一级目录
                            var getFirstItem = uow.FirstProjectRepository.Get(x => x.Id == Id);
                            uow.FirstProjectRepository.Delete(getFirstItem);
                            uow.SaveChanges();
                        }                      
                    }
                     return RedirectToAction("Index");
            }  
            return View();
        }
    

2、但是若是要删除的数据有个三五万,10万20万那该如何,若采用上述方法,保守估计也得10分钟吧,不信,你可以写个程序,打开SQL Server Profiler试一下,这时,若你不想另外配置连接字符串,可以借用EF的连接字符串,使用ADO.NET 完成批量删除功能

 .net Framework 3.5

public static void DeleteObject(SqlBtmsModel context, string deleteString)

{

    var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;

    var factoryProperty = typeof(EntityConnection).GetProperty("StoreProviderFactory", bindingFlags);

    var factory = factoryProperty.GetValue(context.Connection, null) as DbProviderFactory;

    var connStr = (context.Connection as EntityConnection).StoreConnection.ConnectionString;

    using (var conn = factory.CreateConnection())

    {

        conn.ConnectionString = connStr;

        conn.Open();

        var cmd = factory.CreateCommand();

        cmd.Connection = conn;

        cmd.CommandText = deleteString;

        cmd.ExecuteNonQuery();

    }

}

Ø  .Net FrameWork 4.0

当然,若是你使用的是  .Net FrameWork 4.0,那你可以使用以下 方式。

using (DB.Entity.StudentDBEntities context = new DB.Entity.StudentDBEntities())
{

context.ExecuteStoreCommand("delete from Students where StudentId = @studentId", new SqlParameter("@studentId", 5));

context.ExecuteStoreCommand("insert into students (StudentName)values (@p1)", new SqlParameter("@p1", "test"));

 }注:3.5不支持此方式。

可能有人,想使用EntityCommand 进行批量删除,但是EntityCommand 仅支持 EntitySql ,问题就在这里了,EntitySql 目前不支持 Insert 、Delete 、Update操作,静等微软的下一步动作吧。

分享到:

发表评论

评论列表