在Entity Framework 中執行T-sql語句


從Entity Framework  4開始在ObjectContext對象上提供了2個方法可以直接執行SQL語句:ExecuteStoreQuery<T>ExecuteStoreCommand。

1、使用ExecuteStoreQuery<T> :通過sql查詢返回object實體,有有許多需要注意:

1.sql = "select * from Payment where Vendor= @vendor";之所以能寫成select *是因為Payment對象的屬性和表的字段命名完全一致,如果不一致的話,需要將表字段取別名,別名需是對象映射的屬性名稱。

2.如果sql語句返回的列少於(具體化)實體的屬性的個數,那么EF在具體化的時候將拋出一個異常如下圖,因此將需要缺少的列補上一些沒有意義的值,以保證在具體乎的時候不會報錯:eg 如圖1,如果sql=”select PaymentId ,Amount from Payment ” 這樣使用context.ExecuteStoreQuery<Payment >(sql, args);那么會報異常,因此需要將Vendor 列補上 。正確的sql=”select PaymentId ,Amount, null as Vendor from Payment”。

3.如果sql 返回的列 多余具體化的實體屬性的個數,那么EF將會忽視多出的列。

4.如果是你返回的表是映射到幾個繼承關系的實體類上,那么返回的行需要具體化到幾個實體上,EF是無法根據識別列來將返回的行具體化到相應的繼承類型上去,這是EF會拋出一個運行時的exception

5.如果實體有complex Type屬性,那么實體對象的實例是無法用ExecuteStoreQuery()來返回的,因為ExcuteStoreQuery()是無法返回一個complex Type的集合的.返回單個complex type是支持的,但是返回的實體對象里包含complex type就不支持。

6.可以返回實體對象屬性的子集,就是說如果對於Payment表,我們查詢返回PaymentId和Amount字段,然后我們定義一個subPayment 實體包含PaymentId和Amount屬性,然后使用ExcuteStoreQuery<subPayment>()

2、使用ExecuteStoreCommand:這個更加靈活,你可以執行Update,Insert,Delete語句。

using (SzmbEntities entity = new SzmbEntities())
{
         var item = entity.Weatherwarnings.OrderByDescending(x=>x.Id)
                    .Where(x => x.PublishTime < now.AddDays(-14))
                    .FirstOrDefault();
          if (item != null)
          {
                string sql = "Delete FROM  [Weatherwarning] where Id < @ID";
                 var args = new DbParameter[] {
                    new SqlParameter { ParameterName = "ID", Value = item.Id}
                 };
                 entity.ExecuteStoreCommand(sql,args);
           }
  }

ExecuteStoreCommand()返回一個int值,影響的行數。

 

相關文章:

Entity Framework 和 AppFabric 中的二級緩存

對Entity Framework應用二級緩存

Performance Considerations for Entity Framework 5

https://github.com/ChrisNanda/EntityFramework.Cache

Entity Framework - Second Level Caching with DbContext

Application using Entity Framework's Code First to dynamically connect to two different databases


免責聲明!

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



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