Mar 19, 2016

C# Joins/Where with Linq and Lambda

I find that if you're familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors:
var id = 1;
var query =
   from post in database.Posts
   join meta in database.Post_Metas on post.ID equals meta.Post_ID
   where post.ID == id
   select new { Post = post, Meta = meta };
If you're really stuck on using lambdas though, your syntax is quite a bit off. Here's the same query, using the LINQ extension methods:
var id = 1;
var query = database.Posts    // your starting point - table in the "from" statement
   .Join(database.Post_Metas, // the source table of the inner join
      post => post.ID,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
      meta => meta.Post_ID,   // Select the foreign key (the second part of the "on" clause)
      (post, meta) => new { Post = post, Meta = meta }) // selection
   .Where(postAndMeta => postAndMeta.Post.ID == id);    // where statement
 
// keys
var results = context.tb1.Join(
                  context.tb2,
                  t1 => new { t1.Col1, t1.Col2, t1.Col3 },
                  t2 => new { t2.Col1, t2.Col2, t2.Col3 },
                  (t1, t2) => new { t1, t2 })
              .Where(o => o.t2.Col1 == col1 
                  && o.t2.Col2 == col2
                  && o.t2.Col4 == someString)
              .Select(o => o.t1);



0 comments:

Post a Comment

Nam Le © 2014 - Designed by Templateism.com, Distributed By Templatelib