通过外键关联两个以上的表

时间:2013-09-14 19:11:34

标签: c# linq linq-to-sql visual-studio-2012 sql-server-2008-r2

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'的定义,也没有扩展方法'Purchase'接受类型为'System.Data.Linq.Table'的第一个参数'(是你错过了使用指令或程序集引用?)

1 个答案:

答案 0 :(得分: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...");
    }
}