开发者

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜