Mostrando las entradas con la etiqueta linq. Mostrar todas las entradas
Mostrando las entradas con la etiqueta linq. Mostrar todas las entradas
sábado, 3 de septiembre de 2011
WCF Service con Linq
1 comentario:
Publicadas por
Carlos Juan
a la/s
3:21 p.m.
Etiquetas:
aspnet,
linq,
linq from sql,
linq to generic List,
wcf
Windows Communication Foundation o WCF, (también conocido como Indigo) es la plataforma de .NET que nos permite el desarrollo de aplicaciones distribuidas,
Fue creado con el fin de permitir una programación rápida de sistemas distribuidos y el desarrollo de aplicaciones basadas en arquitecturas orientadas a servicios (también conocido como SOA),
Los wcf viene a reemplazar a los web service.
Comparación de los servicios web ASP.NET con el WCF basado en desarrollo
Ejemplo paso a paso.
1.) Crear el proyecto, para eso, File - new web site y mostrara la siguiente ventana, elija un nombre y precione OK.
2.) Agregar un Linq Classes, Add->New Item, elija el LinqToSql Classes,mostrara la siguiente ventana, agregue el nombre de Nortwind.dbml.
3.) Desde server Explorer Arrastren la tabla clientes:
4.) Creación de la interface, dirijase al ventana de Solution explorer y habra el archivo IService.cs
Abra el archivo y agregue el siguiente codigo dentro del dela función
public interface IService Ejemplo:
[OperationContract]
5.) Implementación de la Internface, para eso abra el archivo Service.cs
Acerque el mouse a la clase y coloquelo sobre el sobre Class IService y cuando aparesca el icono en forma de hoja precione clic en Implement interface 'IService1' Ejemplo:public class Service : IService
{
6.) Ingresando codigo del Methodo, luego del paso 5 se habra agregado el siguiente codigo:
1.- Hacemos clic derecho en la Solución y agregamos un nuevo proyecto Web Asp.Net.
File - new web site
2.- Ahora añadimos un Service Reference a nuestra aplicación Web haciendo clic derecho a nuestro proyecto, luego debido a que nuestro cliente está en una misma Solución, descubrimos si existe algún servicio en la solución y la agregamos dando clic en OK, hagámoslo como se muestra a continuación:
3.- Añadiremos una pagina para utilizar la referencia.
4.- Agregaremos controles a la pagina
5.- Por ultimo el código para llamar al wcf
Ver
Fue creado con el fin de permitir una programación rápida de sistemas distribuidos y el desarrollo de aplicaciones basadas en arquitecturas orientadas a servicios (también conocido como SOA),
Los wcf viene a reemplazar a los web service.
Comparación de los servicios web ASP.NET con el WCF basado en desarrollo
Ejemplo paso a paso.
1.) Crear el proyecto, para eso, File - new web site y mostrara la siguiente ventana, elija un nombre y precione OK.
2.) Agregar un Linq Classes, Add->New Item, elija el LinqToSql Classes,mostrara la siguiente ventana, agregue el nombre de Nortwind.dbml.
3.) Desde server Explorer Arrastren la tabla clientes:
4.) Creación de la interface, dirijase al ventana de Solution explorer y habra el archivo IService.cs
Abra el archivo y agregue el siguiente codigo dentro del dela función
public interface IService Ejemplo:
[OperationContract]
List<customer>GetCustomersCountry(string Country);
5.) Implementación de la Internface, para eso abra el archivo Service.cs
Acerque el mouse a la clase y coloquelo sobre el sobre Class IService y cuando aparesca el icono en forma de hoja precione clic en Implement interface 'IService1' Ejemplo:public class Service : IService
{
6.) Ingresando codigo del Methodo, luego del paso 5 se habra agregado el siguiente codigo:
public List<customer> GetCustomersCountry(string Country){ NortwindDataContext db = new NortwindDataContext(); var query = from cust in db.Customers where cust.Country.StartsWith(Country) select cust; return query.ToList(); }Web Cliente - Para Utilizar el WCF
1.- Hacemos clic derecho en la Solución y agregamos un nuevo proyecto Web Asp.Net.
File - new web site
2.- Ahora añadimos un Service Reference a nuestra aplicación Web haciendo clic derecho a nuestro proyecto, luego debido a que nuestro cliente está en una misma Solución, descubrimos si existe algún servicio en la solución y la agregamos dando clic en OK, hagámoslo como se muestra a continuación:
3.- Añadiremos una pagina para utilizar la referencia.
4.- Agregaremos controles a la pagina
5.- Por ultimo el código para llamar al wcf
protected void Button1_Click(object sender, EventArgs e) { ServiceReference1.ServiceClient servicio = new ServiceReference1.ServiceClient(); var query = servicio.GetCustomersCountry(TextBox1.Text);
servicio.Close();
var query1 = from c in query
select new
{
c.CustomerID,
c.CompanyName,
c.Country,
c.Phone,
c.Fax
};
GridView1.DataSource = query1;
DataBind();
}
Detalles de las características de WCF
Nombre del Articulo Original:
Using Linq To SQL With WCF Service
domingo, 17 de octubre de 2010
Convertir Linq a un DataTable ( LINQ To DataTable)
Yo sé que Ado .net está obsoleto, aun así puede llegar hacer útil, sin embargo les sigo recomendando que usen linq o entity, se los juro van a trabajar menos.
DataClassesDataContext db = new DataClassesDataContext();
var query= from c in db.Customers
select new {c.CustomerID, c.CompanyName, c.ContactName, c.Country,c.City };
IDbCommand cmd = db.GetCommand(query as IQueryable);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = (SqlCommand)cmd;
DataTable dt = new DataTable("sd");
try
{
cmd.Connection.Open();
adapter.FillSchema(dt, SchemaType.Source);
adapter.Fill(dt);
}
finally
{
cmd.Connection.Close();
}
Ver
DataClassesDataContext db = new DataClassesDataContext();
var query= from c in db.Customers
select new {c.CustomerID, c.CompanyName, c.ContactName, c.Country,c.City };
IDbCommand cmd = db.GetCommand(query as IQueryable);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = (SqlCommand)cmd;
DataTable dt = new DataTable("sd");
try
{
cmd.Connection.Open();
adapter.FillSchema(dt, SchemaType.Source);
adapter.Fill(dt);
}
finally
{
cmd.Connection.Close();
}
domingo, 27 de junio de 2010
Extendiendo Linq
No hay comentarios.:
Publicadas por
Carlos Juan
a la/s
4:19 p.m.
Etiquetas:
aspnet,
linq,
linq from sql,
linq para sql
Voy iniciar el post haciendo el un ejemplo linq desde el principio y luego mostrare la parte extendida.
1.) Iniciar Visual Studio
2.) File - New web site - Agregar nombre al website
3.) Website – Add new element - LINQ SQL Clasess
Le preguntara si quiere pasar su nueva clase linq a la carpeta App_Code elija si.
4.) Abra su clase Nortwind.dbml y baje del server explorer de la base datos nortwind las tablas:
Category, Producs, Supliers
5.) Cree una clase con el nombre NortwindDataContext.cs, para lograrlo
Website – Add new element – Class
Nota:
El nombre NortwindDataContext es el mismo nombre que del contexto de linq Nortwind.dbml, le mostrar un error:
Este error es normal ya que ambos objetos tiene el mismo nombre, pero la idea es basicamente esa ya que sera 1 solo objeto.
6.)Para que ambos sean un solo objeto tenemos que agregar la palabra partial, con esto logramos que aun que sea un clase separada realmente estoy dentro del contexto, aun los va salir un error ya que hay que quitar el constructor.
Ejemplo:
7.) Ahora procederemos a extender nuestro contexto:
Pueden notar que no hace falta instanciar el contexto esto es porque están adentro del él.
8.) Como usarlo,tiene que crear la pagina: Menu Website - add new element
9.) Ahora a la pagina creada le agregaremos 2 griview y un textbox:
10.) Agregando codigo:
Para gregar codigo solo precione click derecho sobre su pagina y view code:
Buento alli F5 listo.
Espero les sirva.
Ver
1.) Iniciar Visual Studio
2.) File - New web site - Agregar nombre al website
3.) Website – Add new element - LINQ SQL Clasess
Le preguntara si quiere pasar su nueva clase linq a la carpeta App_Code elija si.
4.) Abra su clase Nortwind.dbml y baje del server explorer de la base datos nortwind las tablas:
Category, Producs, Supliers
5.) Cree una clase con el nombre NortwindDataContext.cs, para lograrlo
Website – Add new element – Class
Nota:
El nombre NortwindDataContext es el mismo nombre que del contexto de linq Nortwind.dbml, le mostrar un error:
6.)Para que ambos sean un solo objeto tenemos que agregar la palabra partial, con esto logramos que aun que sea un clase separada realmente estoy dentro del contexto, aun los va salir un error ya que hay que quitar el constructor.
Ejemplo:
7.) Ahora procederemos a extender nuestro contexto:
Pueden notar que no hace falta instanciar el contexto esto es porque están adentro del él.
8.) Como usarlo,tiene que crear la pagina: Menu Website - add new element
9.) Ahora a la pagina creada le agregaremos 2 griview y un textbox:
10.) Agregando codigo:
Para gregar codigo solo precione click derecho sobre su pagina y view code:
Buento alli F5 listo.
Espero les sirva.
domingo, 23 de mayo de 2010
LINQ Generic List con columnas especificas
No hay comentarios.:
Publicadas por
Carlos Juan
a la/s
12:07 a.m.
Etiquetas:
aspnet,
linq,
linq from sql,
linq para sql,
linq to generic List
Para poder ultilizar el resultado de un Query Linq se pueden utilizar las listas genericas Ejemplos:
public List < customer > GetCustomersCountry(string Country)
{
NortwindDataContext db = new NortwindDataContext();
var query = from cust in db.Customers
select cust;
return query.ToList();
}
public List< customer > GetCustomersCountry(string Country)
{
NortwindDataContext db = new NortwindDataContext();
List < customer > c = (from cust in db.Customers
select cust).ToList< customer >();
return c;
}
Sin embargo si no quieren enviar todas filas si no que algunas, se podria modifica facilmente asi:
public List< customer > GetCustomersCountry(string Country)
{
NortwindDataContext db = new NortwindDataContext();
var query = from cust in db.Customers
select new { cust.CustomerID,cust.CompanyName};
return query.ToList();
}
Pero este le dara el error:
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List'
Esto es por que Usted no debe devolver instancias anónimas.
No se pueden devolver los tipos anónimos.
Solución:
public IQueryable GetCustomersCountry()
{
NortwindDataContext db = new NortwindDataContext();
IQueryable I =
(
from c in db.Customers
orderby c.CompanyName
select new { CompanyName = c.CompanyName }
);
return I;
}
Ver
public List < customer > GetCustomersCountry(string Country)
{
NortwindDataContext db = new NortwindDataContext();
var query = from cust in db.Customers
select cust;
return query.ToList();
}
public List< customer > GetCustomersCountry(string Country)
{
NortwindDataContext db = new NortwindDataContext();
List < customer > c = (from cust in db.Customers
select cust).ToList< customer >();
return c;
}
Sin embargo si no quieren enviar todas filas si no que algunas, se podria modifica facilmente asi:
public List< customer > GetCustomersCountry(string Country)
{
NortwindDataContext db = new NortwindDataContext();
var query = from cust in db.Customers
select new { cust.CustomerID,cust.CompanyName};
return query.ToList();
}
Pero este le dara el error:
Cannot implicitly convert type 'System.Collections.Generic.List
Esto es por que Usted no debe devolver instancias anónimas.
No se pueden devolver los tipos anónimos.
Solución:
public IQueryable GetCustomersCountry()
{
NortwindDataContext db = new NortwindDataContext();
IQueryable I =
(
from c in db.Customers
orderby c.CompanyName
select new { CompanyName = c.CompanyName }
);
return I;
}
miércoles, 14 de abril de 2010
LINQ paralelo ( PLINQ ) para SQL server
No hay comentarios.:
Publicadas por
Carlos Juan
a la/s
6:05 p.m.
Etiquetas:
aspnet,
linq,
linq from sql,
linq para sql,
plinq para sql
Ejecución de consultas en procesadores multinúcleo con Linq
Lo primero es que no corre con el framework 3.5 tiene que trasladarse ya al 4.0
Los procesadores multinúcleo ya están aquí. Los procesadores multinúcleo solo estaba disponibles para servidores y PCs de escritorio. Pero ahora, ya se están usando en teléfonos móviles y PDA, lo cual genera grandes ventajas en relación con el consumo de energía. En respuesta al aumento de disponibilidad de plataformas con procesadores multinúcleo, Parallel Language Integrated Query (PLINQ) ofrece una manera fácil de sacar partido del uso de hardware paralelo, incluidos equipos tradicionales con varios procesadores y la última ola de procesadores multinúcleo.
PLINQ es un motor de ejecución de consultas que acepta cualquier consulta LINQ to Objects o LINQ to XML y usa automáticamente varios procesadores o núcleos para su ejecución cuando estos están disponibles. El cambio en el modelo de programación es minúsculo, lo cual significa que no es necesario ser un gurú para usarlo.
Usar PLINQ es casi exactamente lo mismo que usar LINQ to Objects y LINQ to XML. Puede usar cualquiera de los operadores disponibles.
Ejemplos con conexión a base de datos.
Linq
var query = from c in db.Customers
where c.Country == "USA"
orderby c.CompanyName
select new { c.CustomerID, c.CompanyName };
plinq
var query = from c in db.Customers.AsParallel()
where c.Country == "USA"
orderby c.CompanyName
select new { c.CustomerID, c.CompanyName };
El genio Joe Duffy es el responsable de desarrollo del equipo Parallel FX de Microsoft y participa habitualmente en el blog www.bluebytesoftware.com/blog. Está escribiendo un libro, Concurrent Programming on Windows, que va a ser publicado por Addison-Wesley.
Articulo original
viernes, 11 de septiembre de 2009
Linq la evolución de ADO .net
2 comentarios:
Publicadas por
Carlos Juan
a la/s
11:04 a.m.
Etiquetas:
aspnet,
linq,
linq from sql,
linq para sql
Una de las grandes novedades de Visual Studio 2008 y de .NET Framework 3.5 es el Language Integrated Query (LINQ) que habilita la definición de consultas integradas en el lenguaje de programación y es una de las piedras angulares de las nuevas versiones de C# y VB. Precisamente. No es facil dejar atras nuestros Dataset y nuestros amigos DataAdapters pero es momento de continuar, un consejo para superar la perdida es que imaginen que adonet(dataset,dataadapter,connection) era su carro viejo que funciona y esta perferto sin embargo salio el nuevo de agencia y que esta mejor, corre mas rapido, es mas eficiente, mas bonito y no daña el ambiente.
asi que para ayudarlos a migrarse les doy unos ejemplos con connecion a bases de datos sql server.
Lo primero es la hacer la connecion para lograr esto agreguen un nuevo item en su proyecto y elijan linq.
ejemplo:

ahora ya agregado el dbml tiene que agregar las tablas del server explorer:

bueno ahora ha jugar:
hagamos queries:
Primero la consulta comun:
DataClassesDataContext db = new DataClassesDataContext();
var clientes = from c in db.Customers
select new {c.CustomerID, c.CompanyName, c.ContactName, c.Country,c.City };
como usar el resultado
usando Bind
GridView1.DataSource = clientes;
GridView1.DataBind();
o leerlo con un ciclo:
foreach (var customer in clientes )
{
Console.WriteLine("Customer {0}: {1}", customer.CustomerId, customer.CompanyName);
}
Like
para usar like tiene que hacer un using System.Data.Linq.SqlClient;
DataClassesDataContext db = new DataClassesDataContext();
var clientes = from c in db.Customers
where SqlMethods.Like(c.Country, "%" + TextBox1.Text + "%")
select new {c.CustomerID, c.CompanyName, c.ContactName, c.Country,c.City };
Concatenar dos campos
var query = from c in db.Customers
where c.customerid==txtcodito.text && c.country=="spain"
select new { c.Nombre, nombrecompleto = string.Format("{0} {1}", c.companyname,c.contactname) };
execute scalar ejemplo con function
string nombre=(from c in db.customers where p.customerid== txtusuario.text select c.companyname).Single();
string nombre=(from c in db.customers
where p.customerid== txtusuario.text select c).Single().companyname;
Group by
var pais = from p in db.Customers
group p by new { p.Country } into r
select new { r.Key.Country };
var rows = from item in TablaEmpleado.AsEnumerable()
group item by
new
{
empid = item["employeeid"].ToString(),
depto = item["DeptoId"].ToString()
}
into g
select new
{
EmpresaId = g.Key. empid,
depto = g.Key. depto,
total = g.Count())
};
Sum en linq
System.Nullable totalFreight =
(from ord in db.Orders
select ord.Freight)
.Sum();
System.Nullable totalUnitsOnOrder =
(from prod in db.Products
select (long)prod.UnitsOnOrder)
.Sum();
in en linq
string[] countries = new string[] { "Guatemala", "USA", "Mexico" };
var customers =from c in context.Customers
where countries.Contains(c.Country)
select c;
comentario:
Eve para que mire que la tomo en cuenta.
Between
var query = from p in db.orders
where p.Fecha >= Convert.ToDateTime(TextBox1.Text) && p.Fecha <= Convert.ToDateTime(TextBox2.Text) select new { p.Fecha };
Distinct
var query = (from c in db.customers
orderby c.country
select c.country).Distinct();
Join
var groupJoinQuery2 =
from category in categories
join prod in products on category.ID equals prod.CategoryID
orderby category.Name
select new
{
Category = category.Name,
Products = prod.Name
};
sub consulta
var groupJoinQuery2 =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
orderby category.Name
select new
{
Category = category.Name,
Products = from prod2 in prodGroup
orderby prod2.Name
select prod2
};
Left Outer Joins
var query = (from p in dc.GetTable()
join pa in dc.GetTable() on p.Id equals pa.PersonId into tempAddresses
from addresses in tempAddresses.DefaultIfEmpty()
select new { p.FirstName, p.LastName, addresses.State });
SQL:
SELECT [t0].[FirstName], [t0].[LastName], [t1].[State] AS [State]
FROM [dbo].[Person] AS [t0]
LEFT OUTER JOIN [dbo].[PersonAddress] AS [t1] ON [t0].[Id] = [t1].[PersonID]
mas ejemplos de join clic aquí
si son de las personas que usan Store Procedure
pues bien es mas facil =)
lo primero que tiene que hacer es bajar el sp de server explorar al contex del linq

codigo:
//Obtaining the data source
var dbNorthwind =new NorthwindDataContext() ;
// Create the query
var query = dbNorthwind.SalesByCategory("Beverages","1997");
// Execute the query
foreach (var c in query)
{
Console.WriteLine(c.ProductName + "," + c.TotalPurchase);
}
// si quiere el store procedure solo retorna un valor, esto lo usan para busquedas o totales.
var query = dbNorthwind.ObtenerCategoria(txtcodigo.text).Single();
return query.categoryname;
// otro ejemplo de llamar store procedure con linq
var contactNames =
from result in db.GetCustomersInCity("London")
select result.ContactName;
foreach (string contactName in contactNames)
{
Console.WriteLine(contactName) ;
}
Las transacciones tambien son soportadas en linq ejemplo:
using(TransactionScope ts = new TransactionScope())
{
db.ExecuteCommand("exec sp_DoSomethingCool");
db.SubmitChanges();
ts.Complete();
}
alternativa:
db.LocalTransaction = db.Connection.BeginTransaction();
{
db.SubmitChanges();
db.LocalTransaction.Commit();
db.AcceptChanges();
}
catch {
db.LocalTransaction.Abort();
throw;
}
finally {
db.LocalTransaction = null;
}
si quiere manejar la concurecnia en este punto, puede guiarse con el siguiente ejemplo:
db.SubmitChanges(ConflictMode.FailOnFirstConflict);
db.SubmitChanges(ConflictMode.ContinueOnConflict);
si quieren usar LINQ con Listas
var custOrders =
from c in db.Customers
join o in db.Orders on c.CustomerID equals o.CustomerID into orders
where c.CustomerID == "ALFKI"
select new {c.ContactName, orders};
var list = custOrders.ToList() ;
foreach (var listItem in list)
{
Console.WriteLine(listItem.ContactName + " has " + listItem.orders.Count() + " orders, which have been shipped to:") ;
foreach (Order order in listItem.orders)
{
Console.WriteLine(" Order shipped to - " + order.ShipCountry) ;
}
}
Listas genericas
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
List customers = GetCustomerList();
var waCustomers =
from c in customers
where c.Region == "R1"
select c;
foreach (var customer in waCustomers) {
Console.WriteLine("Customer {0}: {1}", customer.CustomerId, customer.CompanyName);
foreach (var order in customer.Orders) {
Console.WriteLine(" Order {0}: {1}", order.Id, order.OrderDate);
}
}
}
static List GetCustomerList() {
List empTree = new List();
empTree.Add(new Product { ProductName = "A", Category = "O", UnitPrice = 12, UnitsInStock = 5, Total = 36, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "B", Category = "O", UnitPrice = 2, UnitsInStock = 4, Total = 35, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "C", Category = "O", UnitPrice = 112, UnitsInStock = 3, Total = 34, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "D", Category = "O", UnitPrice = 112, UnitsInStock = 0, Total = 33, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "E", Category = "O", UnitPrice = 1112, UnitsInStock = 2, Total = 32, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "F", Category = "O", UnitPrice = 11112, UnitsInStock = 0, Total = 31, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
List l = new List();
l.Add(new Customer { CompanyName = "A", Region = "R1", UnitsInStock = 1, Orders = empTree, CustomerId =0});
l.Add(new Customer { CompanyName = "B", Region = "R2", UnitsInStock = 2, Orders = empTree, CustomerId = 1 });
l.Add(new Customer { CompanyName = "C", Region = "R3", UnitsInStock = 3, Orders = empTree, CustomerId = 2 });
l.Add(new Customer { CompanyName = "D", Region = "R4", UnitsInStock = 4, Orders = empTree, CustomerId = 3 });
l.Add(new Customer { CompanyName = "E", Region = "R5", UnitsInStock = 5, Orders = empTree, CustomerId = 4 });
return l;
}
}
class Customer : IComparable {
public string CompanyName { get; set; }
public string Region { get; set; }
public List Orders { get; set; }
public int UnitsInStock { get; set; }
public int CustomerId { get; set; }
public override string ToString() {
return String.Format("Id: {0}, Name: {1}, Region: {3}", this.CustomerId, this.CompanyName, this.Region);
}
int IComparable.CompareTo(Customer other) {
if (other == null)
return 1;
if (this.CustomerId > other.CustomerId)
return 1;
if (this.CustomerId < other.CustomerId) return -1; return 0; } } class Product : IComparable {
public string ProductName { get; set; }
public string Category { get; set; }
public int UnitPrice { get; set; }
public int UnitsInStock { get; set; }
public int Total { get; set; }
public DateTime OrderDate { get; set; }
public int Id { get; set; }
public override string ToString() {
return String.Format("Id: {0}, Name: {1} , Category: {3}", this.Id, this.ProductName, this.Category);
}
int IComparable.CompareTo(Product other) {
if (other == null)
return 1;
if (this.Id > other.Id)
return 1;
if (this.Id < other.Id) return -1; return 0; } } http://www.java2s.com/Code/CSharp/LINQ/Useforeachlooptodealwiththeresultfromlinq.htm
Ver
asi que para ayudarlos a migrarse les doy unos ejemplos con connecion a bases de datos sql server.
Lo primero es la hacer la connecion para lograr esto agreguen un nuevo item en su proyecto y elijan linq.
ejemplo:
ahora ya agregado el dbml tiene que agregar las tablas del server explorer:
bueno ahora ha jugar:
hagamos queries:
Primero la consulta comun:
DataClassesDataContext db = new DataClassesDataContext();
var clientes = from c in db.Customers
select new {c.CustomerID, c.CompanyName, c.ContactName, c.Country,c.City };
como usar el resultado
usando Bind
GridView1.DataSource = clientes;
GridView1.DataBind();
o leerlo con un ciclo:
foreach (var customer in clientes )
{
Console.WriteLine("Customer {0}: {1}", customer.CustomerId, customer.CompanyName);
}
Like
para usar like tiene que hacer un using System.Data.Linq.SqlClient;
DataClassesDataContext db = new DataClassesDataContext();
var clientes = from c in db.Customers
where SqlMethods.Like(c.Country, "%" + TextBox1.Text + "%")
select new {c.CustomerID, c.CompanyName, c.ContactName, c.Country,c.City };
Concatenar dos campos
var query = from c in db.Customers
where c.customerid==txtcodito.text && c.country=="spain"
select new { c.Nombre, nombrecompleto = string.Format("{0} {1}", c.companyname,c.contactname) };
execute scalar ejemplo con function
string nombre=(from c in db.customers where p.customerid== txtusuario.text select c.companyname).Single();
string nombre=(from c in db.customers
where p.customerid== txtusuario.text select c).Single().companyname;
Group by
var pais = from p in db.Customers
group p by new { p.Country } into r
select new { r.Key.Country };
var rows = from item in TablaEmpleado.AsEnumerable()
group item by
new
{
empid = item["employeeid"].ToString(),
depto = item["DeptoId"].ToString()
}
into g
select new
{
EmpresaId = g.Key. empid,
depto = g.Key. depto,
total = g.Count())
};
Sum en linq
System.Nullable
(from ord in db.Orders
select ord.Freight)
.Sum();
System.Nullable
(from prod in db.Products
select (long)prod.UnitsOnOrder)
.Sum();
in en linq
string[] countries = new string[] { "Guatemala", "USA", "Mexico" };
var customers =from c in context.Customers
where countries.Contains(c.Country)
select c;
comentario:
Eve para que mire que la tomo en cuenta.
Between
var query = from p in db.orders
where p.Fecha >= Convert.ToDateTime(TextBox1.Text) && p.Fecha <= Convert.ToDateTime(TextBox2.Text) select new { p.Fecha };
Distinct
var query = (from c in db.customers
orderby c.country
select c.country).Distinct();
var query = (from c in db.customers
select c.country).Distinct().OrderByDescending(x=>x.country);
Join
var groupJoinQuery2 =
from category in categories
join prod in products on category.ID equals prod.CategoryID
orderby category.Name
select new
{
Category = category.Name,
Products = prod.Name
};
sub consulta
var groupJoinQuery2 =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
orderby category.Name
select new
{
Category = category.Name,
Products = from prod2 in prodGroup
orderby prod2.Name
select prod2
};
Left Outer Joins
var query = (from p in dc.GetTable
join pa in dc.GetTable
from addresses in tempAddresses.DefaultIfEmpty()
select new { p.FirstName, p.LastName, addresses.State });
SQL:
SELECT [t0].[FirstName], [t0].[LastName], [t1].[State] AS [State]
FROM [dbo].[Person] AS [t0]
LEFT OUTER JOIN [dbo].[PersonAddress] AS [t1] ON [t0].[Id] = [t1].[PersonID]
mas ejemplos de join clic aquí
si son de las personas que usan Store Procedure
pues bien es mas facil =)
lo primero que tiene que hacer es bajar el sp de server explorar al contex del linq

codigo:
//Obtaining the data source
var dbNorthwind =new NorthwindDataContext() ;
// Create the query
var query = dbNorthwind.SalesByCategory("Beverages","1997");
// Execute the query
foreach (var c in query)
{
Console.WriteLine(c.ProductName + "," + c.TotalPurchase);
}
// si quiere el store procedure solo retorna un valor, esto lo usan para busquedas o totales.
var query = dbNorthwind.ObtenerCategoria(txtcodigo.text).Single();
return query.categoryname;
// otro ejemplo de llamar store procedure con linq
var contactNames =
from result in db.GetCustomersInCity("London")
select result.ContactName;
foreach (string contactName in contactNames)
{
Console.WriteLine(contactName) ;
}
Las transacciones tambien son soportadas en linq ejemplo:
using(TransactionScope ts = new TransactionScope())
{
db.ExecuteCommand("exec sp_DoSomethingCool");
db.SubmitChanges();
ts.Complete();
}
alternativa:
db.LocalTransaction = db.Connection.BeginTransaction();
{
db.SubmitChanges();
db.LocalTransaction.Commit();
db.AcceptChanges();
}
catch {
db.LocalTransaction.Abort();
throw;
}
finally {
db.LocalTransaction = null;
}
si quiere manejar la concurecnia en este punto, puede guiarse con el siguiente ejemplo:
db.SubmitChanges(ConflictMode.FailOnFirstConflict);
db.SubmitChanges(ConflictMode.ContinueOnConflict);
si quieren usar LINQ con Listas
var custOrders =
from c in db.Customers
join o in db.Orders on c.CustomerID equals o.CustomerID into orders
where c.CustomerID == "ALFKI"
select new {c.ContactName, orders};
var list = custOrders.ToList() ;
foreach (var listItem in list)
{
Console.WriteLine(listItem.ContactName + " has " + listItem.orders.Count() + " orders, which have been shipped to:") ;
foreach (Order order in listItem.orders)
{
Console.WriteLine(" Order shipped to - " + order.ShipCountry) ;
}
}
Listas genericas
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
List
var waCustomers =
from c in customers
where c.Region == "R1"
select c;
foreach (var customer in waCustomers) {
Console.WriteLine("Customer {0}: {1}", customer.CustomerId, customer.CompanyName);
foreach (var order in customer.Orders) {
Console.WriteLine(" Order {0}: {1}", order.Id, order.OrderDate);
}
}
}
static List
List
empTree.Add(new Product { ProductName = "A", Category = "O", UnitPrice = 12, UnitsInStock = 5, Total = 36, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "B", Category = "O", UnitPrice = 2, UnitsInStock = 4, Total = 35, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "C", Category = "O", UnitPrice = 112, UnitsInStock = 3, Total = 34, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "D", Category = "O", UnitPrice = 112, UnitsInStock = 0, Total = 33, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "E", Category = "O", UnitPrice = 1112, UnitsInStock = 2, Total = 32, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "F", Category = "O", UnitPrice = 11112, UnitsInStock = 0, Total = 31, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
List
l.Add(new Customer { CompanyName = "A", Region = "R1", UnitsInStock = 1, Orders = empTree, CustomerId =0});
l.Add(new Customer { CompanyName = "B", Region = "R2", UnitsInStock = 2, Orders = empTree, CustomerId = 1 });
l.Add(new Customer { CompanyName = "C", Region = "R3", UnitsInStock = 3, Orders = empTree, CustomerId = 2 });
l.Add(new Customer { CompanyName = "D", Region = "R4", UnitsInStock = 4, Orders = empTree, CustomerId = 3 });
l.Add(new Customer { CompanyName = "E", Region = "R5", UnitsInStock = 5, Orders = empTree, CustomerId = 4 });
return l;
}
}
class Customer : IComparable
public string CompanyName { get; set; }
public string Region { get; set; }
public List
public int UnitsInStock { get; set; }
public int CustomerId { get; set; }
public override string ToString() {
return String.Format("Id: {0}, Name: {1}, Region: {3}", this.CustomerId, this.CompanyName, this.Region);
}
int IComparable
if (other == null)
return 1;
if (this.CustomerId > other.CustomerId)
return 1;
if (this.CustomerId < other.CustomerId) return -1; return 0; } } class Product : IComparable
public string ProductName { get; set; }
public string Category { get; set; }
public int UnitPrice { get; set; }
public int UnitsInStock { get; set; }
public int Total { get; set; }
public DateTime OrderDate { get; set; }
public int Id { get; set; }
public override string ToString() {
return String.Format("Id: {0}, Name: {1} , Category: {3}", this.Id, this.ProductName, this.Category);
}
int IComparable
if (other == null)
return 1;
if (this.Id > other.Id)
return 1;
if (this.Id < other.Id) return -1; return 0; } } http://www.java2s.com/Code/CSharp/LINQ/Useforeachlooptodealwiththeresultfromlinq.htm
Suscribirse a:
Entradas (Atom)




