Lingua

Procedura: Connettersi a un database

Importante

Non usare System.Data.SqlClient per nuovi sviluppi. Usare Microsoft.Data.SqlClient per il nuovo codice di accesso ai dati SQL Server. Questi esempi mantengono System.Data.SqlClient perché il provider LINQ to SQL predefinito di .NET Framework lo richiede. La modifica del tipo di connessione da sola non esegue la migrazione di LINQ to SQL.

DataContext è il canale principale tramite il quale ci si connette a un database, si recuperano oggetti da esso e si inviano le modifiche al database. Si usa esattamente DataContext come si userebbe un ADO.NET SqlConnection. In effetti, DataContext viene inizializzato con una connessione o una stringa di connessione fornita dall'utente. Per altre informazioni, vedere Metodi DataContext (Progettazione O/R).

Lo scopo di DataContext è quello di convertire le richieste di oggetti in query SQL da eseguire nel database e quindi assemblare oggetti dai risultati. DataContext abilita Language-Integrated Query (LINQ) implementando lo stesso modello di operatore degli operatori di query standard, ad esempio Where e Select.

Importante

Il mantenimento di una connessione sicura è della massima importanza. Per altre informazioni, vedere Sicurezza in LINQ to SQL.

Esempio 1

Nell'esempio seguente, DataContext viene usato per connettersi al database di esempio Northwind e recuperare righe di clienti la cui città è Londra.

// Do not use System.Data.SqlClient for new development; use Microsoft.Data.SqlClient.
// LINQ to SQL's built-in provider requires System.Data.SqlClient.
// DataContext takes a connection string.
DataContext db = new DataContext(@"c:\Northwind.mdf");

// Get a typed table to run queries.
Table<Customer> Customers = db.GetTable<Customer>();

// Query for customers from London.
var query =
    from cust in Customers
    where cust.City == "London"
    select cust;

foreach (var cust in query)
    Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);
' Do not use System.Data.SqlClient for new development; use Microsoft.Data.SqlClient.
' LINQ to SQL's built-in provider requires System.Data.SqlClient.
' DataContext takes a connection string.
Dim db As New DataContext("…\Northwind.mdf")

' Get a typed table to run queries.
Dim Customers As Table(Of Customer) = db.GetTable(Of Customer)()

' Query for customer from London.
Dim Query = _
    From cust In Customers _
    Where cust.City = "London" _
    Select cust

For Each cust In Query
    Console.WriteLine("id=" & cust.CustomerID & _
        ", City=" & cust.City)
Next

Ogni tabella di database è rappresentata come una Table raccolta disponibile tramite il GetTable metodo , usando la classe di entità per identificarla.

Esempio 2

La procedura consigliata consiste nel dichiarare un oggetto fortemente tipizzato DataContext anziché basarsi sulla classe di base DataContext e sul GetTable metodo . Un tipo fortemente tipizzato DataContext dichiara tutte le raccolte Table come membri del contesto, come nell'esempio seguente.

// Do not use System.Data.SqlClient for new development; use Microsoft.Data.SqlClient.
// LINQ to SQL's built-in provider requires System.Data.SqlClient.
public partial class Northwind : DataContext
{
    public Table<Customer> Customers;
    public Table<Order> Orders;
    public Northwind(string connection) : base(connection) { }
}
' Do not use System.Data.SqlClient for new development; use Microsoft.Data.SqlClient.
' LINQ to SQL's built-in provider requires System.Data.SqlClient.
Partial Public Class Northwind
    Inherits DataContext
    Public Customers As Table(Of Customer)
    Public Orders As Table(Of Order)
    Public Sub New(ByVal connection As String)
        MyBase.New(connection)
    End Sub
End Class

È quindi possibile esprimere la query per i clienti di Londra più semplicemente come:

// Do not use System.Data.SqlClient for new development; use Microsoft.Data.SqlClient.
// LINQ to SQL's built-in provider requires System.Data.SqlClient.
Northwnd db = new Northwnd(@"c:\Northwnd.mdf");
var query =
    from cust in db.Customers
    where cust.City == "London"
    select cust;
foreach (var cust in query)
    Console.WriteLine("id = {0}, City = {1}", cust.CustomerID,
        cust.City);
' Do not use System.Data.SqlClient for new development; use Microsoft.Data.SqlClient.
' LINQ to SQL's built-in provider requires System.Data.SqlClient.
Dim db As New Northwind("...\Northwnd.mdf")

Dim query = _
    From cust In db.Customers _
    Where cust.City = "London" _
    Select cust

For Each cust In query
    Console.WriteLine("id=" & cust.CustomerID & _
        ", City=" & cust.City)
Next

Vedere anche