EntityFramework執行SQL語句


在EF中執行Sql語句

Insert Code:
using ( var context = new EFRecipesEntities())
{
   string sql = @"insert into Chapter3.Payment(Amount, Vendor)
                     values (@Amount, @Vendor)";
   var args = new DbParameter [] {
                   new SqlParameter { ParameterName = "Amount" , Value = 99.97 M },
                   new SqlParameter { ParameterName = "Vendor" , Value = "Ace Plumbing" }
                 };
   int rowCount = context . ExecuteStoreCommand( sql , args);
}

 

select all code:
using ( var context = new EFRecipesEntities())
{
   string sql = "select * from Chapter3.Student where Degree = @Major";
   var args = new DbParameter [] {
                  new SqlParameter { ParameterName = "Major" , Value = "Masters" }};
   var students = context . ExecuteStoreQuery < Student >( sql , args);
   Console . WriteLine( "Students...");
   foreach ( var student in students)
   {
     Console . WriteLine( "{0} {1} is working on a {2} degree" ,
   student . FirstName , student . LastName , student . Degree);
  }
}

 

select specific column
using ( var conn = new EntityConnection( "name=EFRecipesEntities"))
{
    var cmd = conn . CreateCommand();
    conn . Open();
    cmd . CommandText = @"select c.Name, C.Email from
                                  EFRecipesEntities.Customers as c";
    using ( var reader = cmd . ExecuteReader( CommandBehavior . SequentialAccess))
     {
       while ( reader . Read())
           {
               Console . WriteLine( "{0}'s email is: {1}" ,
                                   reader . GetString( 0 ), reader . GetString( 1));
          }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM