简体   繁体   中英

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!

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 }

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 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.

It's possible to join tables using linq:

Eg :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM