LINQ提供了查询表达式,它使用SQL风格的语句执行查询并生成结果集。然后,可以遍历这个结果集并进行相应的处理。为了使用LINQ,被查询的对象必须是"可枚举"的,它们必须实现了IEnumerable接口的集合。LINQ to SQL能根据你定义的类创建它自己的可枚举对象集合,这些类直接映射到数据库中的表,它们称为实体类。DataContext类负责实体类与数据库中表的关系,DataContext对象能自动控制数据库连接。
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "(local)";// ".\\MSSQLSERVER";
builder.InitialCatalog = "Northwind";
builder.IntegratedSecurity = true;
Northwind northwindDB = new Northwind(builder.ConnectionString);
try
{
Console.WriteLine("Please enter a customer ID(5 characters):");
string customerId = Console.ReadLine();
var ordersQuery = from o in northwindDB.Orders where String.Equals(o.CustomerID, customerId) select o;
foreach(var order in ordersQuery)
{
if (order.ShippedDate == null)
{
Console.WriteLine("Order {0} not yet shipped\n\n", order.OrderID);
}
else
{
Console.WriteLine("Order: {0}\nPlaced:{1}\nShipped: {2}\n" +
"To Address: {3}\n{4}\n{5}\n{6}\n\n", order.OrderID, order.OrderDate, order.ShippedDate,
order.ShipName,order.ShipAddress, order.ShipCity, order.ShipCountry);
}
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error accessing the database: {0}", ex.Message);
Console.ReadLine();
}
[Table(Name ="Orders")]
public class Order
{
[Column(IsPrimaryKey =true,CanBeNull =false)]
public int OrderID { get; set; }
[Column]
public string CustomerID { get; set; }
[Column]
public DateTime? OrderDate { get; set; }
[Column]
public DateTime? ShippedDate { get; set; }
[Column]
public string ShipName { get; set; }
[Column]
public string ShipAddress { get; set; }
[Column]
public string ShipCity { get; set; }
[Column]
public string ShipCountry { get; set; }
}
public class Northwind : DataContext
{
public Table<Order> Orders;
public Northwind(string connectionInfo):base(connectionInfo)
{
}
}