Search code examples
c#linqlinq-to-sqlvisual-studio-2012sql-server-2008-r2

Relating More than two tables through foreign keys


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
)

First above is an sql script through my sql server management studio to create two tables (Customer and Purchase).Then the following classes is added to the C# code as follows.

[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;
}

This is the main function.

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);

And it's giving me an error on the foreach statement.

Error 1 'System.Data.Linq.Table' does not contain a definition for 'Purchase' and no extension method 'Purchase' accepting a first argument of type 'System.Data.Linq.Table' could be found (are you missing a using directive or an assembly reference?)


Solution

  • You have no association defined on your LINQ Table definitions. It would look something like this for your situation:

    [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; }
    
    }
    

    You can then enumerate your customers like so:

    var customers = customerTable.ToList();
    
    foreach (Customer customer in customers)
    {
        foreach (Purchase purchase in customer.Purchases)
        {
            Console.WriteLine("My data here...");
        }
    }