Condividi tramite


Operazioni eseguibili con LINQ to SQL

LINQ to SQL supporta tutte le funzionalità principali usate dagli sviluppatori SQL. È possibile creare query per ottenere informazioni ed eseguire operazioni di inserimento, aggiornamento ed eliminazione di dati dalle tabelle.

Selezionare:

Per eseguire una selezione (proiezione) è sufficiente scrivere una query LINQ nel proprio linguaggio di programmazione e successivamente eseguirla per recuperare i risultati. In LINQ to SQL tutte le operazioni indispensabili vengono convertite nelle operazioni SQL necessarie con cui si ha dimestichezza. Per altre informazioni, vedere LINQ to SQL.

Nell'esempio seguente i nomi di società dei clienti dell'area londinese vengono recuperati e visualizzati nella finestra della console.

// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(@"northwnd.mdf");
// or, if you are not using SQL Server Express
// Northwnd nw = new Northwnd("Database=Northwind;Server=server_name;Integrated Security=SSPI");

var companyNameQuery =
    from cust in nw.Customers
    where cust.City == "London"
    select cust.CompanyName;

foreach (var customer in companyNameQuery)
{
    Console.WriteLine(customer);
}
' Northwnd inherits from System.Data.Linq.DataContext.
Dim nw As New Northwnd("c:\northwnd.mdf")
' or, if you are not using SQL Server Express
' Dim nw As New Northwnd("Database=Northwind;Server=dschwart7;Integrated Security=SSPI")

Dim companyNameQuery = _
    From cust In nw.Customers _
    Where cust.City = "London" _
    Select cust.CompanyName

For Each customer In companyNameQuery
    Console.WriteLine(customer)
Next

Inserimento

Per eseguire un'operazione InsertSQL, aggiungere semplicemente oggetti al modello a oggetti creato e chiamare SubmitChanges su DataContext.

Nell'esempio seguente vengono aggiunti un nuovo cliente e informazioni sul cliente alla tabella Customers usando InsertOnSubmit.

// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(@"northwnd.mdf");

Customer cust = new Customer();
cust.CompanyName = "SomeCompany";
cust.City = "London";
cust.CustomerID = "98128";
cust.PostalCode = "55555";
cust.Phone = "555-555-5555";
nw.Customers.InsertOnSubmit(cust);

// At this point, the new Customer object is added in the object model.
// In LINQ to SQL, the change is not sent to the database until
// SubmitChanges is called.
nw.SubmitChanges();
' Northwnd inherits from System.Data.Linq.DataContext.
Dim nw As New Northwnd("c:\northwnd.mdf")

Dim cust As New Customer With {.CompanyName = "SomeCompany", _
    .City = "London", _
    .CustomerID = 98128, _
    .PostalCode = 55555, .Phone = "555-555-5555"}
nw.Customers.InsertOnSubmit(cust)
' At this point, the new Customer object is added in the object model.
' In LINQ to SQL, the change is not sent to the database until
' SubmitChanges is called.
nw.SubmitChanges()

Aggiornamento

Per eseguire un'operazione Update per una voce del database, recuperare innanzitutto tale voce e modificarla direttamente nel modello a oggetti. Dopo avere modificato l'oggetto, chiamare SubmitChanges su DataContext per aggiornare il database.

Nell'esempio seguente vengono recuperati tutti i clienti dell'area londinese. Il nome della città viene quindi modificato da "London" in "London - Metro", infine viene chiamato SubmitChanges per inviare le modifiche al database.

Northwnd nw = new Northwnd(@"northwnd.mdf");

var cityNameQuery =
    from cust in nw.Customers
    where cust.City.Contains("London")
    select cust;

foreach (var customer in cityNameQuery)
{
    if (customer.City == "London")
    {
        customer.City = "London - Metro";
    }
}
nw.SubmitChanges();
Dim nw As New Northwnd("c:\northwnd.mdf")
Dim cityNameQuery = _
    From cust In nw.Customers _
    Where cust.City.Contains("London") _
    Select cust

For Each customer In cityNameQuery
    If customer.City = "London" Then
        customer.City = "London - Metro"
    End If
Next
nw.SubmitChanges()

Deleting

Per eseguire un'operazione Delete per un elemento, rimuovere l'elemento dalla raccolta a cui appartiene, quindi chiamare SubmitChanges su DataContext per eseguire il commit della modifica.

Nota

LINQ to SQL non riconosce le operazioni di eliminazione a catena. Per eliminare una riga in una tabella con vincoli, vedere Procedura: eliminare righe dal database.

Nell'esempio seguente il cliente con il codice CustomerID98128 viene recuperato dal database. Quindi, dopo la conferma che la riga del cliente è stata recuperata, viene chiamato DeleteOnSubmit per rimuovere quell'oggetto dalla raccolta. Infine viene chiamato SubmitChanges per inoltrare l'operazione di eliminazione al database.

Northwnd nw = new Northwnd(@"northwnd.mdf");
var deleteIndivCust =
    from cust in nw.Customers
    where cust.CustomerID == "98128"
    select cust;

if (deleteIndivCust.Count() > 0)
{
    nw.Customers.DeleteOnSubmit(deleteIndivCust.First());
    nw.SubmitChanges();
}
Dim nw As New Northwnd("c:\northwnd.mdf")
Dim deleteIndivCust = _
    From cust In nw.Customers _
    Where cust.CustomerID = 98128 _
    Select cust

If deleteIndivCust.Count > 0 Then
    nw.Customers.DeleteOnSubmit(deleteIndivCust.First)
    nw.SubmitChanges()
End If

Vedi anche