It is believed that many comrades who use EF already know how to run SQL commands in EF.
I would like to summarize here, I hope you learn EF help! In the first version of EF (. NET3.5SP1), we can only convert the objectcontext.connection to EntityConnection, and then Entityconnection.storeconnection converted to SqlConnection. With this SqlConnection, we will be able to run the SQL command again by creating SqlCommand. (Personally feel really annoying, hehe) For example: EntityConnection entityconnection=(entityconnection) ctx.
Connection; DbConnection storeconnection=entityconnection.storeconnection; DbCommand cmd=Storeconnection.createcommand (); Cmd.commandtype=System.Data.CommandType.StoredProcedure; Cmd.commandtext="[Pro_user_digitalcard_check]";
。。。。。。。 In the EF4 (. NET4), we have a brand new API:ObjectContext.ExecuteStoreCommand (...) and objectcontext.executestorequery<t>(...).
It is not difficult to know from a function name that the former is to execute a SQL command with no return set, such as a update,delete operation, which executes a query and can convert the return set to an object. using(varCTX =NewMyobjectcontext ()) {ctx. Executestorecommand ("UPDATE person SET Name = ' Michael ' WHERE PersonID = 1"); Copy the Codeusing(varCTX =NewMyobjectcontext ()) {
varPeopleviews = ctx. Executestorequery<personview> ("SELECT PersonID, Name from person"); }
Public classPersonview { Public intPersonID {Get;Set; } Public stringName {Get;Set; } The replication code now has EF4.1, the name of the API has changed slightly. If DbContext ObjectContext is packaged, then Dbcontext.database is the package that corresponds to the database-side information. The Execute SQL command also naturally starts with the database type. corresponding to Executestorecommand and executestorequery<t> are Database.executesqlcommand and database.sqlquery<t>.. using(varCTX =NewMydbcontext ()) {ctx. Database.executesqlcommand ("UPDATE person SET Name = ' Michael ' WHERE PersonID = 1"); Copy the Codeusing(varCTX =NewMydbcontext ()) {
varPeopleviews = ctx. Sqlquery<personview> ("SELECT PersonID, Name from person").
ToList (); }
Public classPersonview { Public intPersonID {Get;Set; } Public stringName {Get;Set; } }
< Span style= "COLOR: #800000" > < Span style= "COLOR: #000000" > < Span style= "COLOR: #0000ff" > < Span style= "COLOR: #000000" > reprint: http://www.cnblogs.com/chengxiaohui/articles/2092001.html
C # runs SQL commands directly in EF