create table Customer
(
ID int not null primary key,
Name varchar(30) not null
)
create table Purchase
(
ID int not null primary key,
CustomerID int references Customer (ID),
Description varchar(30) not null,
Price decimal not null
)
首先上面是一个sql脚本通过我的sql server management studio创建两个表(Customer和Purchase)。然后在C#代码中添加如下类如下。
[Table(Name = "Customer")]
public class Customer
{
[Column(IsPrimaryKey = true)]
public int ID;
[Column(Name = "Name")]
public string Name;
}
[Table(Name = "Purchase")]
public class Purchase
{
[Column(IsPrimaryKey = true)]
public int ID;
[Column]
public int CustomerID;
[Column]
public string Descriptions;
[Column]
public decimal Price;
}
这是主要功能。
DataContext dataContext = new DataContext(@"Server=.\SQLEXPRESS;Database=master;Trusted_Connection=True;");
Table<Customer> customers = dataContext.GetTable<Customer>();
foreach (Purchase p in customers.Purchases)
Console.WriteLine(p.Price);
它在 foreach 语句上给了我一个错误。
错误 1“System.Data.Linq.Table”不包含“Purchase”的定义,并且找不到接受“System.Data.Linq.Table”类型的第一个参数的扩展方法“Purchase”(您是否缺少使用指令还是程序集引用?)