LINQ to Entities 查询注意事项

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这个地方时,会报异常。

原文地址:https://www.cnblogs.com/yezuhui/p/6842235.html