How to use join using linq to sql in C#?

i want some sample code on this


  • oh i found one code example ,
    var LeaveTypes = (from l in BlogDbContext.LeaveType
    join e in BlogDbContext.User
    on new { PID = l.AddedBy } equals new { PID = e.UserId }
    select new
    TypeId = l.TypeId,
    LeaveTitle = l.LeaveTitle,
    Description = l.Description,
    AddedBy = l.AddedBy,
    UpdateBy = l.UpdateBy,
    CreatedDate = l.CreatedDate,
    UpdateDate = l.UpdateDate,
    CreatedBy = e.UserName


    example reference...

    website :

  • You could go two ways with this. Using LINQPad (invaluable if you're new to LINQ) and a dummy database, I built the following queries:

    post => post.Post_id,
    meta => meta.Post_id,
    (post, meta) => new { Post = post, Meta = meta }


    from p in Posts
    join pm in Post_metas on p.Post_id equals pm.Post_id
    select new { Post = p, Meta = pm }

    In this particular case, I think the LINQ syntax is clearer.

    The thing I'd like to point out though is that if you have appropriate foreign keys in your database, (between post and post_meta) then you probably don't need an explicit join unless you're trying to load a large number of records. Your example seems to indicate that you are trying to load a single post and it's meta data. Assuming that there are many post_meta records for each post, then you could do the following:

    var post = Posts.Single(p => p.ID == 1);
    var metas = post.Post_metas.ToList();

  • You may go through the following link for help:

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!