9. LINQ – .NET Language Integrated
Query
• Consulta integrada
– Metadados
– Sintaxe em tempo de compilação
– Tipagem estática
– IntelliSense
• Operadores
– Padrão
– Customizáveis
• avaliação remota, tradução de consultas, otimização, etc
10. Arquitetura
C# VB.NET Others
.NET Language Integrated Query (LINQ)
LINQ data source providers
ADO.NET support for LINQ
LINQ LINQ LINQ LINQ LINQ
to Objects to Datasets to SQL to Entities to XML
11. Base de Desenvolvimento
• .Net Framework 3
• Visual Studio 2005 ou superior
• Sql Server 2005 Express ou superior- Freeware
12. Programação Sem LINQ
• public static IEnumerable GetMyData()
{
using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
using (SqlCommand myCommand = myConnection.CreateCommand())
{
myCommand.CommandText = "SELECT * FROM dbo.myTable";
using (SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand))
{
DataTable resultTable = new DataTable();
myAdapter.Fill(resultTable);
return resultTable.Rows;
}
}
}
}
13. Com LINQ
• public static IEnumerable GetMyData()
{
using (var myContext = new MyDataContext())
{
return myContext.Clients;
}
}
14. LINQ to SQL
• // DataContext takes a connection string
var db = new DataContext("c:northwindnorthwnd.mdf");
// Get a typed table to run queries
Table<Customer> Customers = db.GetTable<Customer>();
// Query for customers from London
var q = from c in Customers where c.City == "London" select c;
foreach (var cust in q)
Console.WriteLine(“City = {0}“, cust.City);
15. Select / Where
• public void Linq1() {
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
from n in numbers
where n < 5
select n;
Console.WriteLine("Numbers < 5:");
foreach (var x in lowNums) {
Console.WriteLine(x);
}
}
16. Insert
Primary Key
public static bool EntityInsert(Entity entity) {
try {
var db = new DataClassesEzDataContext();
db.Entities.InsertOnSubmit(entity);
db.SubmitChanges();
return true;
}
catch {return false;}
}
17. Update
• var dc = new BO.DataClassesEzDataContext();
• var user = Utils.User;
• user.password =
Utils.Encript(passwordBoxNew.Password);
• dc.Users.Attach(user, true);
• dc.SubmitChanges();
18. Delete
• Northwnd db = new Northwnd(@"c:Northwnd.mdf");
// Query for a specific customer.
var cust = (from c in db.Customers where c.CustomerID == "ALFKI" select
c).First();
// Removing it from the table also removes it from the Customer’s list.
db.Orders.DeleteOnSubmit(cust);
// Ask the DataContext to save all the changes.
db.SubmitChanges();
19. Inner Join
• var q = from c in db.Funcionarios
join o in db.Orders on
c. FuncionarioId equals o.FuncionarioId
where c.Cidade == “Joinville"
select o;
20. Transaction
• System.Data.Common.DbTransaction trans = null;
• var dc = new DataClassesUdescDataContext();
• try {
• dc.Connection.Open();
• trans = dc.Connection.BeginTransaction();
• dc.Transaction = trans;
• //...
• trans.Commit();
• }
• catch {
• if (trans != null) trans.Rollback();
• }
• finally {
• // Close the connection
• if (objDataClass.Connection.State == ConnectionState.Open)
• objDataClass.Connection.Close();
• }
21. Operadores
Agregação Conversão Ordenação Particionamento Sets
Aggregate Cast OrderBy Skip Concat
Average OfType ThenBy SkipWhile Distinct
Count ToArray Descending Take Except
Max ToDictionary Reverse TakeWhile Intersect
Min ToList Union
Sum ToLookup
ToSequence
33. LINQ - .NET FRAMEWORK 4.0
• Performance
• Usabilidade
• Conversão automática de enumeradores
• Associação com campo que não seja chave primária
• Herança
• Query Stability
• Auto referência não causa estouro de pilha.
• Update Stability
• General Stability
• SQL Metal
• LINQ do SQL class designer
• Code Generation (SQL Metal + LINQ to SQL Class Designer)