Problemas conocidos y consideraciones en LINQ to EntitiesKnown Issues and Considerations in LINQ to Entities

Esta sección proporciona información sobre problemas conocidos con LINQ a consultas de entidades.This section provides information about known issues with LINQ to Entities queries.

Consultas LINQ que no se pueden almacenar en memoria cachéLINQ Queries That cannot be Cached

A partir de .NET Framework 4.0.5, las consultas LINQ to Entities se almacenan automáticamente en memoria caché.Starting with .NET Framework 4.5, LINQ to Entities queries are automatically cached. Sin embargo, as consultas LINQ to Entities que aplican el operador Enumerable.Contains a colecciones en memoria no se almacenan en memoria caché automáticamente.However, LINQ to Entities queries that apply the Enumerable.Contains operator to in-memory collections are not automatically cached. Tampoco se permite parametrizar colecciones en memoria en consultas LINQ compiladas.Also parameterizing in-memory collections in compiled LINQ queries is not allowed.

Pérdida de información de ordenaciónOrdering Information Lost

Proyección de columnas en un tipo anónimo provocará la información de ordenación se perderá en algunas consultas que se ejecutan en una base de datos de SQL Server 2005 que se establece en un nivel de compatibilidad de "80".Projecting columns into an anonymous type will cause ordering information to be lost in some queries that are executed against a SQL Server 2005 database set to a compatibility level of "80". Esto se produce cuando un nombre de columna en la lista ORDER BY coincide con un nombre de columna en el selector, como se muestra en el ejemplo siguiente:This occurs when a column name in the order-by list matches a column name in the selector, as shown in the following example:

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    // Ordering information is lost when executed against a SQL Server 2005
    // database running with a compatibility level of "80".
    var results = context.Contacts.SelectMany(c => c.SalesOrderHeaders)
        .OrderBy(c => c.SalesOrderDetails.Count)
        .Select(c => new { c.SalesOrderDetails.Count });

    foreach (var result in results)
        Console.WriteLine(result.Count);

}
Using context As New AdventureWorksEntities()
    ' Ordering information is lost when executed against a SQL Server 2005
    ' database running with a compatibility level of "80".
    Dim results = context.Contacts.SelectMany(Function(c) c.SalesOrderHeaders) _
        .OrderBy(Function(c) c.SalesOrderDetails.Count) _
        .Select(Function(c) New With {c.SalesOrderDetails.Count})

    For Each result In results
        Console.WriteLine(result.Count)
    Next
End Using

Enteros sin signo no admitidosUnsigned Integers Not Supported

No se admite la especificación de un tipo entero sin signo en una consulta LINQ to Entities porque el Entity FrameworkEntity Framework no admite enteros sin signo.Specifying an unsigned integer type in a LINQ to Entities query is not supported because the Entity FrameworkEntity Framework does not support unsigned integers. Si especifica un entero sin signo, un ArgumentException excepción se producirá durante la conversión de expresión de consulta, como se muestra en el ejemplo siguiente.If you specify an unsigned integer, an ArgumentException exception will be thrown during the query expression translation, as shown in the following example. En este ejemplo se consulta un pedido cuyo número de identificación (Id.) es 48000.This example queries for an order with ID 48000.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    uint s = UInt32.Parse("48000");

    IQueryable<SalesOrderDetail> query = from sale in context.SalesOrderDetails
                                         where sale.SalesOrderID == s
                                         select sale;

    // NotSupportedException exception is thrown here.
    try
    {
        foreach (SalesOrderDetail order in query)
            Console.WriteLine("SalesOrderID: " + order.SalesOrderID);
    }
    catch (NotSupportedException ex)
    {
        Console.WriteLine("Exception: {0}", ex.Message);
    }
}
Using context As New AdventureWorksEntities()
    Dim saleId As UInteger = UInt32.Parse("48000")

    Dim query = _
        From sale In context.SalesOrderDetails _
        Where sale.SalesOrderID = saleId _
        Select sale

    Try
        ' NotSupportedException exception is thrown here.
        For Each order As SalesOrderDetail In query
            Console.WriteLine("SalesOrderID: " & order.SalesOrderID)
        Next
    Catch ex As NotSupportedException
        Console.WriteLine("Exception: " + ex.Message)
    End Try
End Using

Errores de la conversión de tiposType Conversion Errors

En Visual Basic, cuando se asigna una propiedad a una columna de tipo bit de SQL Server con un valor de 1 utilizando la función CByte, se produce una excepción SqlException con el mensaje "Error de desbordamiento aritmético".In Visual Basic, when a property is mapped to a column of SQL Server bit type with a value of 1 using the CByte function, a SqlException is thrown with an "Arithmetic overflow error" message. En el ejemplo siguiente se consulta la columna Product.MakeFlag en la base de datos de ejemplo AdventureWorks y se produce una excepción cuando tiene lugar una iteración en los resultados de la consulta.The following example queries the Product.MakeFlag column in the AdventureWorks sample database and an exception is thrown when the query results are iterated over.

Using context As New AdventureWorksEntities()
    Dim productsList = _
        From product In context.Products _
        Select CByte(product.MakeFlag)

    ' Throws an SqlException exception with a "Arithmetic overflow error 
    ' for data type tinyint" message when a value of 1 is iterated over.
    For Each makeFlag In productsList
        Console.WriteLine(makeFlag)
    Next
End Using

Referencia a variables no escalares no admitidaReferencing Non-Scalar Variables Not Supported

En una consulta no se puede hacer referencia a variables no escalares, tales como una entidad.Referencing a non-scalar variables, such as an entity, in a query is not supported. Cuando este tipo de consulta se ejecuta, se genera una excepción NotSupportedException con un mensaje que indica "No se puede crear un valor constante de tipo EntityType".When such a query executes, a NotSupportedException exception is thrown with a message that states "Unable to create a constant value of type EntityType. Sólo los tipos primitivos ('como Int32, String y Guid') se admiten en este contexto.".Only primitive types ('such as Int32, String, and Guid') are supported in this context."

Nota

Permite hacer referencia a una colección de variables escalares.Referencing a collection of scalar variables is supported.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    Contact contact = context.Contacts.FirstOrDefault();

    // Referencing a non-scalar closure in a query will
    // throw an exception when the query is executed.
    IQueryable<string> contacts = from c in context.Contacts
        where c == contact
        select c.LastName;

    try
    {
        foreach (string name in contacts)
        {
            Console.WriteLine("Name: ", name);
        }
    }
    catch (NotSupportedException ex)
    {
        Console.WriteLine(ex.Message);
    }
}
Using context As New AdventureWorksEntities()

    Dim contact As Contact = context.Contacts.FirstOrDefault()

    ' Referencing a non-scalar closure in a query will
    ' throw an exception when the query is executed.
    Dim contacts = From c In context.Contacts _
                   Where c.Equals(contact) _
                   Select c.LastName

    Try
        For Each name As String In contacts
            Console.WriteLine("Name: ", name)
        Next

    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try

End Using

Se puede producir un error en consultas anidadas con SQL Server 2000Nested Queries May Fail with SQL Server 2000

Con SQL Server 2000, se puede producir un error en consultas LINQ to Entities si se generan consultas Transact-SQL anidadas con tres o más niveles de profundidad.With SQL Server 2000, LINQ to Entities queries may fail if they produce nested Transact-SQL queries that are three or more levels deep.

Proyectar a un tipo anónimoProjecting to an Anonymous Type

Si define su ruta de acceso de consultas inicial para incluir objetos relacionados utilizando el método Include sobre ObjectQuery<T> y, a continuación, utiliza LINQ para proyectar los objetos devueltos sobre un tipo anónimo, los objetos especificados en el método de inclusión no se incluyen en los resultados de la consulta.If you define your initial query path to include related objects by using the Include method on the ObjectQuery<T> and then use LINQ to project the returned objects to an anonymous type, the objects specified in the include method are not included in the query results.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    var resultWithoutRelatedObjects =
        context.Contacts.Include("SalesOrderHeaders").Select(c => new { c }).FirstOrDefault();
    if (resultWithoutRelatedObjects.c.SalesOrderHeaders.Count == 0)
    {
        Console.WriteLine("No orders are included.");
    }
}
Using context As New AdventureWorksEntities()
    Dim resultWithoutRelatedObjects = context.Contacts. _
        Include("SalesOrderHeaders"). _
        Select(Function(c) New With {c}).FirstOrDefault()
    If resultWithoutRelatedObjects.c.SalesOrderHeaders.Count = 0 Then
        Console.WriteLine("No orders are included.")
    End If
End Using

Para obtener objetos relacionados, no proyecte los tipos devueltos sobre un tipo anónimo.To get related objects, do not project returned types to an anonymous type.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    var resultWithRelatedObjects =
        context.Contacts.Include("SalesOrderHeaders").Select(c => c).FirstOrDefault();
    if (resultWithRelatedObjects.SalesOrderHeaders.Count != 0)
    {
        Console.WriteLine("Orders are included.");
    }
}
Using context As New AdventureWorksEntities()
    Dim resultWithRelatedObjects = context.Contacts. _
        Include("SalesOrderHeaders"). _
        Select(Function(c) c).FirstOrDefault()
    If resultWithRelatedObjects.SalesOrderHeaders.Count <> 0 Then
        Console.WriteLine("Orders are included.")
    End If
End Using

Vea tambiénSee also