简体   繁体   English

将Linq中的两个表连接到SQL

[英]Join two tables in Linq to SQL

Maybe a quite easy question but I'm new in Linq to SQL. 也许是一个非常简单的问题,但我是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? 我想要一个查询,例如: userID=3然后给出所有细节(FirstName,LastName etc)我如何加入这两个表? I would prefer C# code if it is possible! 如果可能,我更喜欢C#代码!

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: 可以使用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 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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