Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join multiple tables?

I have the following classes. I have a object var of Description class. I want to select Balance related to the Client provided in the var object using Linq to Sql or Lambda expression. How to join these tables to get the Balance from Account table?

public class Description
    {
        public int DescriptionID { get; set; }

       // Attributes

        public int ClientID { get; set; }

        [ForeignKey("ClientID")]
        public virtual Client Client { get; set; }


    }

public class Client
    {
        public int ClientID { get; set; }

       // Attributes

        public int UserID { get; set; }

        [ForeignKey("UserID")]
        public virtual User User { get; set; }

    }

 public class User
    {
        public int UserID { get; set; }

       // Attributes

     }

 public class Account
    {

        public int AccountID { get; set; }

        [Required, Column("Balance"), Display(Name = "Account Balance")]
        public double Balance { get; set; }


        public int UserID { get; set; }

        [ForeignKey("UserID")]
        public virtual User User { get; set; }

    }
like image 460
nebula Avatar asked Jun 26 '12 09:06

nebula


People also ask

Can we join multiple tables in SQL?

It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.

Can multiple tables join?

As you can see, joining three tables in SQL isn't as hard as it sounds. In fact, you can join as many tables as you like – the idea behind it is the same as joining only two tables. It's very helpful to take a look at the data midstep and imagine that the tables you've already joined are one table.


1 Answers

You could try this:

var balance = (from a in context.Accounts
               join c in context.Clients on a.UserID equals c.UserID
               where c.ClientID == yourDescriptionObject.ClientID
               select a.Balance)
              .SingleOrDefault();

Or - if you only have the DescriptionID:

var balance = (from a in context.Accounts
               join c in context.Clients on a.UserID equals c.UserID
               join d in context.Descriptions on c.ClientID equals d.ClientID
               where d.DescriptionID == yourDescriptionID
               select a.Balance)
              .SingleOrDefault();

(Or FirstOrDefault() or ToList() or Sum()? Because your model would allow that clients/descriptions are related to multiple accounts ...)

like image 186
Slauma Avatar answered Sep 29 '22 01:09

Slauma