1. Using Entity Framework to delete data is a headache. to delete a small amount of data, use the following methods:
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. But if the data to be deleted has a value of 3, 50 thousand, and 0.1 million, what should we do? If we adopt the above method, it will take 10 minutes to keep it for a conservative estimate. Believe it or not, you can writeProgramOpen SQL Server Profiler and try it. If you do not want to configure another connection string, you can use the EF connection string and use ADO. Net to delete the data in batches.
. 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
Of course, if you are using. NET Framework 4.0, you can use the following methods.
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 "));
} Note: 3.5 does not support this method.
Some people may want to use entitycommand for batch deletion, but entitycommand only supports entitysql. The problem is here. entitysql currently does not support insert, delete, update, and wait for Microsoft's next actions.