Executes the SQL statement in the EF.
using(varContext =Newefrecipesentities ()) { stringsql =@"INSERT INTO Chapter3.payment (Amount, Vendor) VALUES (@Amount, @Vendor)"; varargs =Newdbparameter[] {NewSqlParameter {parametername ="Amount", Value =99.97M}, NewSqlParameter {parametername ="Vendor", value="Ace Plumbing"} }; intRowCount =context. Executestorecommand (sql, args);}
using(varContext =Newefrecipesentities ()) { stringsql ="SELECT * from chapter3.student where degree = @Major"; varargs =Newdbparameter[] {NewSqlParameter {parametername ="Major", Value ="Masters"}}; varStudents = context. Executestorequery<student>(sql, args); Console.WriteLine ("Students ..."); foreach(varStudentinchstudents) {Console.WriteLine ("{0} {1} is working on a {2} degree", student. FirstName, student. LastName, student. degree); }}
using(varconn =NewEntityConnection ("name=efrecipesentities")){ varcmd =Conn. CreateCommand (); Conn. Open (); Cmd.commandtext=@"Select C.name, c.email from Efrecipesentities.customers as C"; using(varReader =cmd. ExecuteReader (commandbehavior.sequentialaccess)) { while(reader. Read ()) {Console.WriteLine ("{0} ' s email is: {1}", reader. GetString (0), reader. GetString (1)); } }}
1.sql = "SELECT * from Payment where vendor= @vendor"; a select * is written because the properties of the Payment object are exactly the same as the field names of the table, and if not, you need to alias the table fields. The alias needs to be the property name of the object map.
2. If the SQL statement returns fewer columns than the (materialized) entity, then EF throws an exception as it materializes, so the missing columns will need to be given meaningless values to ensure that no error is made at the exact time: eg 1, if sql= "select Paymentid , Amount from Payment "uses the context. Executestorequery<payment > (sql, args); Then the exception is reported, so the vendor column needs to be mended. The correct sql= "select Paymentid, Amount, null as Vendor from Payment".
3. If the columns returned by SQL are extra materialized for the number of entity attributes, then EF ignores the extra columns.
EntityFramework Executing SQL statements