Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two tables in Linq to SQL

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!

like image 271
dali1985 Avatar asked Dec 06 '22 22:12

dali1985


2 Answers

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 }
like image 116
Pleun Avatar answered Dec 09 '22 10:12

Pleun


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
            };
like image 45
Stuart Avatar answered Dec 09 '22 11:12

Stuart