Join two tables in Linq to SQL

22,680

Solution 1

You do not have to do all the plumbing yourself. If you have the right foreign keys in the database you will not have to join yourself.

You can just do:

var query = from u in db.Users
select new { User = u;
FirstName = u.UserTables.FirstName }

Solution 2

for an inner join use something like:

var query = from u in db.Users
            join ut in db.UserTables on u.UserId equals ut.UserId
            select new
            {
                User = u,
                Extra = ut
            };

Solution 3

It's possible to join tables using linq:

E.g :

var test = (from a in DataContext.User 
    join b in DataContext.UserTable on a.UserId equals b.UserId 
    select new 
    {                       
        UserId = a.UserId,
        FirstName = b.FirstName
        LastName = b.LastName
    }).ToList();

Regards

Solution 4

Like this perhaps:

var joinedResult = from u in context.User
                   join u2 in context.UserTable on u.UserId equals u2.UserId
                   select new {
                      UserId = u.UserId,
                      FirstName = u2.FirstName
                   };

I guess your example is just an example, right? Cause it doesn't make much sense splitting that data into two tables.

Share:
22,680
dali1985
Author by

dali1985

Updated on March 23, 2020

Comments

  • dali1985
    dali1985 about 4 years

    Maybe a quite easy question but I'm new in Linq to SQL. I have two tables

    User : UserId,name,Password,Email
    USER_TABLE: Id, UserId, FirstName,LastName......
    

    I would like a query that gives for example: userID=3 then give all the details (FirstName,LastName etc) How can I join these two tables? I would prefer C# code if it is possible!