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

问题描述 投票:0回答:2
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 server management studio创建两个表(Customer和Purchase)的sql脚本。然后将以下类添加到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”(您是否缺少using 指令还是程序集引用?)

c# linq linq-to-sql visual-studio-2012 sql-server-2008-r2
2个回答
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...");
    }
}

0
投票

AKTOBA HADA LJAWAB MN ALAM AKHAR!

© www.soinside.com 2019 - 2024. All rights reserved.