查询表达式语法示例:元素运算符 (LINQ to Entities)

本主题中的示例演示如何使用 First 方法通过使用查询表达式语法以查询 AdventureWorks 销售模型。 这些示例中使用的 AdventureWorks 销售模型从 AdventureWorks 示例数据库中的 Contact、Address、Product、SalesOrderHeader 和 SalesOrderDetail 等表生成。

本主题中的示例使用下面的 using/Imports 语句:

Option Explicit On
Option Strict On
Imports System.Data.Objects
Imports System.Globalization
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Globalization;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Common;

First

示例

以下示例使用 First 方法以返回其名字为“Brooke”的第一个联系人。

Dim firstName = "Brooke"
Using context As New AdventureWorksEntities
    Dim contacts As ObjectSet(Of Contact) = context.Contacts

    Dim query As Contact = ( _
        From cont In contacts _
        Where cont.FirstName = firstName _
        Select cont).First()

    Console.WriteLine("ContactID: " & query.ContactID)
    Console.WriteLine("FirstName: " & query.FirstName)
    Console.WriteLine("LastName: " & query.LastName)
End Using
string firstName = "Brooke";
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = context.Contacts;

    Contact query = (
        from contact in contacts
        where contact.FirstName == firstName
        select contact)
        .First();

    Console.WriteLine("ContactID: " + query.ContactID);
    Console.WriteLine("FirstName: " + query.FirstName);
    Console.WriteLine("LastName: " + query.LastName);
}

另请参见

概念

LINQ to Entities 中的查询