Entity Framework Core Tutorial Query di base
Entity Framework Core utilizza Language Integrate Query (LINQ) per interrogare i dati dal database.
- LINQ consente di utilizzare C # (o il tuo linguaggio .NET preferito) per scrivere query fortemente tipizzate in base al contesto derivato e alle classi di entità.
- La ricerca in Entity Framework Core rimane la stessa di EF 6 per caricare entità dal database.
- Fornisce query SQL ottimizzate e la possibilità di includere funzioni C # / VB.NET in query LINQ-to-Entities.
Diciamo che abbiamo un modello semplice che contiene tre entità.
public class Customer { public int CustomerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public virtual List<Invoice> Invoices { get; set; } }
Carica tutti i dati
Nell'esempio seguente vengono caricati tutti i dati dalla tabella Customers
.
using (var context = new MyContext()) { var customers = context.Customers.ToList(); }
Carica una singola entità
Nell'esempio seguente viene caricato un singolo record dalla tabella Customers
base a CustomerId
.
using (var context = new MyContext()) { var customers = context.Customers .Single(c => c.CustomerId == 1); }
Filtra i dati
L'esempio seguente carica tutti i clienti con il marchio FirstName
.
using (var context = new MyContext()) { var customers = context.Customers .Where(c => c.FirstName == "Mark") .ToList(); }