The database connection string is opened to the Entity framework, which can be used to directly obtain the connection string and then perform related operations. If in the process of use, found in the Entity Framework, there are some unmet needs, then you can use this connection string, you write ADO code, go to the database for related operations. In particular, for some complex queries, it is common to simply execute an SQL statement and return a result set. Here is a method that returns a DataTable directly.
<summary>///EF SQL statement returns datatable///</summary>///<param name= "db" ></param>///<param Name= "SQL" ></param>///<param name= "parameters" ></param>///<returns></returns> public static DataTable sqlqueryfordatatatable (this Database db,string sql,sqlparameter[] parameters) {SqlConnection conn = new System.Data.SqlClient.SqlConnection (); Conn. ConnectionString = db. CONNECTION.CONNECTIONSTRING;IF (Conn. state! = ConnectionState.Open) {Conn. Open ();} SqlCommand cmd = new SqlCommand (); cmd. Connection = Conn;cmd.commandtext = sql;if (parameters. Length > 0) {foreach (var item in parameters) {cmd. Parameters.Add (item);}} SqlDataAdapter adapter = new SqlDataAdapter (cmd);D atatable table = new DataTable (); adapter. Fill (table); return table;}
Then call the time, directly into the context of the database in, you can.
Method Two, write the extension method of the class
public static class Dbextend {public static DataTable Select_table_info (this dbentities model, string sql, Sqlpa rameter[] Parameters) { SqlConnection conn = new System.Data.SqlClient.SqlConnection (); Conn. ConnectionString = model. Database.Connection.ConnectionString; IF (Conn. state! = ConnectionState.Open) { Conn. Open (); } SqlCommand cmd = new SqlCommand (); Cmd. Connection = conn; Cmd.commandtext = SQL; if (Parameters!=null && parameters. Length >0) foreach (var item in Parameters) { cmd. Parameters.Add (item); } SqlDataAdapter adapter = new SqlDataAdapter (cmd); DataTable table = new DataTable (); Adapter. Fill (table); return table; } }
Entity Framework Execution SQL statement returns DataTable