共用方式為


查詢運算式語法範例:元素運算子 (LINQ to Entities)

本主題中的範例將示範如何使用 First 方法,透過查詢運算式語法來查詢 AdventureWorks Sales Model。 這些範例中使用的 AdventureWorks Sales Model 是從 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 中的查詢