dali1985
dali1985

Reputation: 3313

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!

Upvotes: 4

Views: 24762

Answers (4)

Crimsonland
Crimsonland

Reputation: 2204

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

Upvotes: 3

Pleun
Pleun

Reputation: 8920

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 }

Upvotes: 6

Stuart
Stuart

Reputation: 66882

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

Upvotes: 4

Mikael Östberg
Mikael Östberg

Reputation: 17156

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.

Upvotes: 2

Related Questions