Entity Framework 大量刪除

來源:互聯網
上載者:User

1、使用 Entity FrameWork  刪除資料,著實是一件比較頭疼的資料,若是少量資料,可以使用以下方法刪除

 

 using (DB.Entity.StudentDBEntities context = new DB.Entity.StudentDBEntities())
            {
                foreach (var item in context.Students.Where(row => row.Isleft == true))
                {
                    context.DeleteObject(item);
                }
                context.SaveChanges();
            }

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操作,靜等微軟的下一步動作吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.