Практическое руководство. Выполнение запроса, возвращающего коллекцию типов-примитивов (платформа Entity Framework)

В этом разделе приведены примеры выполнения запросов, возвращающих коллекцию примитивных типов. Чтобы вернуть только один объект, можно использовать один из следующих методов поверх запроса: First, FirstOrDefault, Single, SingleOrDefault.

Один и тот же пример приводится с использованием всех следующих технологий запросов платформы Entity Framework .

  • LINQ to Entities

  • Сущность Entity SQL с ObjectQuery<T>

  • Методы построителя запросов ObjectQuery<T>

Пример в этом разделе основан на модели Adventure Works Sales. Чтобы запустить код, используемый в данном разделе, нужно сначала добавить к проекту модель Adventure Works Sales и настроить его для использования платформы Entity Framework. Дополнительные сведения см. в разделе Как использовать мастер моделей EDM (Entity Framework) или Как вручную настроить проект Entity Framework и Как определить модель EDM вручную (Entity Framework).

Пример

Далее приведен пример LINQ to Entities .

Dim contactId As Integer = 377

Using context As New AdventureWorksEntities()
    ' Select a value. 
    Dim orders As ObjectSet(Of SalesOrderHeader) = context.SalesOrderHeaders

    Dim orderQuery As IQueryable(Of Int32) = From order In orders _
        Where order.Contact.ContactID = contactId _
        Select order.PurchaseOrderNumber.Length

    ' Iterate through the collection of values. 
    For Each result As Int32 In orderQuery
        Console.WriteLine("{0}", result)
    Next

    ' Use a nullable DateTime value because ShipDate can be null. 
    Dim shipDateQuery As IQueryable(Of System.Nullable(Of DateTime)) = From order In orders _
        Where order.Contact.ContactID = contactId _
        Select order.ShipDate

    ' Iterate through the collection of values. 
    For Each shipDate As System.Nullable(Of DateTime) In shipDateQuery
        Dim shipDateMessage As String = "date not set"

        If shipDate IsNot Nothing Then
            shipDateMessage = shipDate.ToString()
        End If
        Console.WriteLine("Ship Date: {0}.", shipDateMessage)
    Next
End Using
int contactId = 377;

using (AdventureWorksEntities context
    = new AdventureWorksEntities())
{
    // Select a value.
    ObjectSet<SalesOrderHeader> orders
        = context.SalesOrderHeaders;

    IQueryable<Int32> orderQuery =
        from order in orders
        where order.Contact.ContactID == contactId
        select order.PurchaseOrderNumber.Length;

    // Iterate through the collection of values.
    foreach (Int32 result in orderQuery)
    {
        Console.WriteLine("{0}", result);
    }

    // Use a nullable DateTime value because ShipDate can be null.
    IQueryable<DateTime?> shipDateQuery =
        from order in orders
        where order.Contact.ContactID == contactId
        select order.ShipDate;

    // Iterate through the collection of values.
    foreach (DateTime? shipDate in shipDateQuery)
    {
        string shipDateMessage = "date not set";

        if (shipDate != null)
        {
            shipDateMessage = shipDate.ToString();
        }
        Console.WriteLine("Ship Date: {0}.", shipDateMessage);
    }
}

Далее приведен пример Entity SQL .

Dim contactId As Integer = 377

Using context As New AdventureWorksEntities()
    Dim orderQueryString As String = "SELECT VALUE Length(order.PurchaseOrderNumber) FROM " & _
        " AdventureWorksEntities.SalesOrderHeaders AS order WHERE order.CustomerID = @contactId"
    Dim shipDateQueryString As String = "SELECT VALUE order.ShipDate" & _
        " FROM AdventureWorksEntities.SalesOrderHeaders AS order WHERE order.CustomerID = @contactId"

    ' Use the SelectValue method to select a value. 
    Dim orderQuery As New ObjectQuery(Of Int32)(orderQueryString, context, MergeOption.NoTracking)
    orderQuery.Parameters.Add(New ObjectParameter("contactId", contactId))

    ' Iterate through the collection of values. 
    For Each result As Int32 In orderQuery
        Console.WriteLine("{0}", result)
    Next

    ' Use a nullable DateTime value because ShipDate can be null. 
    Dim shipDateQuery As New ObjectQuery(Of Nullable(Of DateTime))(shipDateQueryString, context, MergeOption.NoTracking)
    shipDateQuery.Parameters.Add(New ObjectParameter("contactId", contactId))

    ' Iterate through the collection of values. 
    For Each shipDate As Nullable(Of DateTime) In shipDateQuery
        Dim shipDateMessage As String = "date not set"

        If shipDate IsNot Nothing Then
            shipDateMessage = shipDate.ToString()
        End If
        Console.WriteLine("Ship Date: {0}.", shipDateMessage)
    Next
End Using
int contactId = 377;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    string orderQueryString = @"SELECT VALUE Length(order.PurchaseOrderNumber)
        FROM AdventureWorksEntities.SalesOrderHeaders AS order
        WHERE order.CustomerID = @contactId";
    string shipDateQueryString = @"SELECT VALUE order.ShipDate
        FROM AdventureWorksEntities.SalesOrderHeaders AS order
        WHERE order.CustomerID = @contactId";

    // Use the SelectValue method to select a value.
    ObjectQuery<Int32> orderQuery =
        new ObjectQuery<Int32>(orderQueryString,
            context, MergeOption.NoTracking);
    orderQuery.Parameters.Add(
        new ObjectParameter("contactId", contactId));

    // Iterate through the collection of values.
    foreach (Int32 result in orderQuery)
    {
        Console.WriteLine("{0}", result);
    }

    // Use a nullable DateTime value because ShipDate can be null.
    ObjectQuery<Nullable<DateTime>> shipDateQuery =
        new ObjectQuery<Nullable<DateTime>>(shipDateQueryString,
    context, MergeOption.NoTracking);
    shipDateQuery.Parameters.Add(
        new ObjectParameter("contactId", contactId));

    // Iterate through the collection of values.
    foreach (Nullable<DateTime> shipDate in shipDateQuery)
    {
        string shipDateMessage = "date not set";

        if (shipDate != null)
        {
            shipDateMessage = shipDate.ToString();
        }
        Console.WriteLine("Ship Date: {0}.", shipDateMessage);
    }
}

Далее приведен пример метода построителя запросов.

Dim contactId As Integer = 377

Using context As New AdventureWorksEntities()
    ' Use the SelectValue method to select a value. 
    Dim orderQuery As ObjectQuery(Of Int32) = context.SalesOrderHeaders.Where("it.CustomerID = @contactId", _
                        New ObjectParameter("contactId", contactId)).SelectValue(Of Int32)("Length(it.PurchaseOrderNumber)")

    ' Iterate through the collection of values. 
    For Each result As Int32 In orderQuery
        Console.WriteLine("{0}", result)
    Next

    ' Use a nullable DateTime value because ShipDate can be null. 
    Dim shipDateQuery As ObjectQuery(Of Nullable(Of DateTime)) = _
        context.SalesOrderHeaders.Where("it.CustomerID = @contactId", _
            New ObjectParameter("contactId", contactId)).SelectValue(Of Nullable(Of DateTime))("it.ShipDate")

    ' Iterate through the collection of values. 
    For Each shipDate As Nullable(Of DateTime) In shipDateQuery
        Dim shipDateMessage As String = "date not set"

        If shipDate IsNot Nothing Then
            shipDateMessage = shipDate.ToString()
        End If
        Console.WriteLine("Ship Date: {0}.", shipDateMessage)
    Next
End Using
int contactId = 377;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // Use the SelectValue method to select a value.
    ObjectQuery<Int32> orderQuery =
        context.SalesOrderHeaders
        .Where("it.CustomerID = @contactId",
        new ObjectParameter("contactId", contactId))
        .SelectValue<Int32>("Length(it.PurchaseOrderNumber)");

    // Iterate through the collection of values.
    foreach (Int32 result in orderQuery)
    {
        Console.WriteLine("{0}", result);
    }

    // Use a nullable DateTime value because ShipDate can be null.
    ObjectQuery<Nullable<DateTime>> shipDateQuery =
        context.SalesOrderHeaders
        .Where("it.CustomerID = @contactId",
            new ObjectParameter("contactId", contactId))
        .SelectValue<Nullable<DateTime>>("it.ShipDate");

    // Iterate through the collection of values.
    foreach (Nullable<DateTime> shipDate in shipDateQuery)
    {
        string shipDateMessage = "date not set";

        if (shipDate != null)
        {
            shipDateMessage = shipDate.ToString();
        }
        Console.WriteLine("Ship Date: {0}.", shipDateMessage);
    }
}

См. также

Задачи

Как выполнить запрос, возвращающий объекты типа сущностей (платформа Entity Framework)
Как выполнить запрос, возвращающий коллекцию анонимных типов (платформа Entity Framework)
Как выполнять параметризованный запрос (платформа Entity Framework)

Основные понятия

Методы построителя запросов (платформа Entity Framework)