0
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”(您是否缺少使用指令还是程序集引用?)

4

1 回答 1

1

您没有在 LINQ 表定义上定义关联。对于您的情况,它看起来像这样:

[Table(Name = "Customer")]
public class Customer
{
    [Column(IsPrimaryKey = true, Name = "ID")]
    public int ID { get; set; }

    [Column(Name = "Name")]
    public string Name { get; set; }

    [Association(Name = "Customer_Purchases", ThisKey = "ID", OtherKey = "CustomerID")]
    public EntitySet<Purchase> PurchaseList { get; set; }

    public List<Purchase> Purchases
    {
        get
        {
            return new List<Purchase>(PurchaseList.AsEnumerable());
        }
    }

}

[Table(Name = "Purchase")]
public class Purchase
{
    [Column(IsPrimaryKey = true, Name = "ID")]
    public int ID { get; set; }

    [Column(Name = "CustomerID")]
    public int CustomerID { get; set; }

    [Column(Name = "Description")]
    public string Description { get; set; }

    [Column(Name = "Price")]
    public decimal Price { get; set; }

}

然后,您可以像这样枚举您的客户:

var customers = customerTable.ToList();

foreach (Customer customer in customers)
{
    foreach (Purchase purchase in customer.Purchases)
    {
        Console.WriteLine("My data here...");
    }
}
于 2013-09-15T02:47:29.607 回答