示例数据库Northwind可到MSDN下载,两个表是放在同一个数据库中的,你可以分开放到不同的服务器上。
下载示例数据库Northwind (LINQ to SQL)
原文件下载:App.rar
代码
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
namespace LinqConsoleApp
{
//参考:http://msdn.microsoft.com/en-us/bb534644%28zh-cn%29.aspx
class App
{
static void Main(string[] args)
{
//建立不同的服务器连接
DataContext cdb = new DataContext(@"server=*****;database=Northwind;uid=sa;pwd=ll");
Table<Customer> customer = cdb.GetTable<Customer>();
DataContext odb = new DataContext(@"server=*****;database=Test;uid=sa;pwd=ll");
Table<Order> order = odb.GetTable<Order>();
//查询表达式
IQueryable<Customer> cq = from c in customer
where c.City == "Berlin"
select c;
IQueryable<Order> oq = from o in order
where o.OrderDate >DateTime.Parse("1997-10-03")
select o;
//转换类型,如果用IQueryable<T>的Join方法连接对出现<查询包含对不同数据上下文上所定义项的引用>错误。
List<Customer> cl = cq.ToList<Customer>();
List<Order> ol = oq.ToList<Order>();
//建立对应关系
var join = cl.Join(ol,
c => c.CustomerID,
o => o.CustomerID,
(c,o) => new
{
CustomerID = c.CustomerID,
City = c.City,
Orders = o.OrderID,
OrderDate = o.OrderDate
});
try
{
foreach (var j in join)
{
Console.WriteLine("CustomerID={0},City={1}, Orders={2},OrderDate={3}",
j.CustomerID, j.City, j.Orders,j.OrderDate);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
}
Console.ReadLine();
}
}
//建立实体类Customers
[Table(Name = "Customers")]
public class Customer
{
[Column]
public string CustomerID
{
get;
set;
}
[Column]
public string City
{
get;
set;
}
}
//建立实体类Orders
[Table(Name = "Orders")]
public class Order
{
[Column]
public int OrderID
{
get;
set;
}
[Column]
public string CustomerID
{
get;
set;
}
[Column]
public DateTime OrderDate
{
get;
set;
}
}
}