要使用LINQ to SQL要完成以下几个步骤
1、先将数据库的表映射一个实体类
1 [Table(Name = "Customers")]
2 class Contact
3 {
4 [Column(IsPrimaryKey=true)]
5 public string CustomerID { set; get; }
6 [Column(Name = "ContactName")]
7 public string Name { set; get; }
8 [Column]
9 public string City { set; get; }
10 }
2、实例化 DataContext,DataContext主要是建立SQL与数据库之间的映射2 class Contact
3 {
4 [Column(IsPrimaryKey=true)]
5 public string CustomerID { set; get; }
6 [Column(Name = "ContactName")]
7 public string Name { set; get; }
8 [Column]
9 public string City { set; get; }
10 }
string connect = "server=.;database=Northwind;uid=sa;pwd=";
DataContext db = new DataContext(connect);
DataContext db = new DataContext(connect);
3、和其他一样了,查询和显示
var contacts = from contact in db.GetTable<Contact>()
where contact.City == "London"
select contact;
foreach (var contact in contacts)
{
Console.WriteLine(contact.Name);
}
where contact.City == "London"
select contact;
foreach (var contact in contacts)
{
Console.WriteLine(contact.Name);
}