LINQ to Entities 查詢註意事項
阿新 • • 發佈:2017-05-08
表達式 信息 null
1> 排序信息丟失
如果在排序操作之後執行了任何其他操作,則不能保證這些附加操作中會保留排序結果。這些操作包括 Select 和 Where 等。另外,采用表達式作為輸入參數的 First 和 FirstOrDefault 方法不保留順序。
如下代碼:並不能達到反序排序的效果
using (var edm = new NorthwindEntities()) { IQueryable<Customers> cc = edm.Customers.OrderByDescending(c => c.CustomerID).Where(c => c.Region != null).Select(c => c); foreach (var c in cc) Console.WriteLine(c.CustomerID); }
2> 不支持無符號整數
由於 實體框架不支持無符號整數,因此不支持在 LINQ to Entities 查詢中指定無符號整數類型。如果指定無符號整數,則在查詢表達式轉換過程中會引發 NotSupportedException異常,並顯示無法創建類型為“結束類型”的常量值。此上下文僅支持基元類型(“例如 Int32、String 和 Guid”)。
如下將會報異常的代碼:
using (var edm = new NorthwindEntities()) { uint id = UInt32.Parse("123"); IQueryable<string> produt = from p in edm.Products where p.UnitPrice == id select p.ProductName; foreach (string name in produt) Console.WriteLine(name); }
上面的代碼中,由於id是uint而不是Int32,String,Guid的標量類型,所以在執行到where p.UnitPrice ==id這個地方時,會報異常。
3> 不支持引用非標量閉包
不支持在查詢中引用非標量閉包(如實體)。在執行這類查詢時,會引發 NotSupportedException 異常,並顯示消息“無法創建類型為“結束類型”的常量值。此上下文中僅支持基元類型(‘如 Int32、String 和 Guid’)
如下將會報異常的代碼:
using (var edm = new NorthwindEntities()) { Customers customer = edm.Customers.FirstOrDefault(); IQueryable<string> cc = from c in edm.Customers where c == customer select c.ContactName; foreach (string name in cc) Console.WriteLine(name); }
上面的代碼中,由於customer是引用類型而不是Int32,String,Guid的標量類型,所以在執行到where c==customer這個地方時,會報異常。
LINQ to Entities 查詢註意事項