4

I'm looking for the counterpart of Msql query:

SELECT per.*,add.addressDescription FROM Persons per 
       JOIN Address add ON per.AddressId = add.AddressId

I have this query:

    var query = persons.JOIN(address,per = person.addressId,add = addressId
    (per,add) => 
    new Persons{
                addressDescription = add.addressDescription,
                PersonId = per.PersonId,
                PersonFirstName = per.PersonFirstName
                PersonLastName = per.PersonLastName})

Is there a way to populate Persons.addressDescription without assigning individually the other properties of Persons? Imagine if Persons have 10 more properties.

I would like to refrain from using loops like:

foreach(Person person in PersonList)
{
  foreach(Address address in AddressList)
  {
     if(person.addressId == address.addressId){
        person.addressDescription = address.addressDescription
     }
   }
}
user3770093
  • 315
  • 2
  • 11
  • 20
  • Possible duplicate of [What is the syntax for an inner join in LINQ to SQL?](http://stackoverflow.com/questions/37324/what-is-the-syntax-for-an-inner-join-in-linq-to-sql) – shA.t Jul 11 '16 at 07:29
  • @shA.t hi and thanks for your reply, the problem is their question only asks how to return the Persons without populating Persons.AddressDescription. – user3770093 Jul 11 '16 at 07:37

2 Answers2

3
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
Gehan Fernando
  • 1,221
  • 13
  • 24
3
var query = persons.join(address,
    per = person.addressId,
    add = addressId
    (per,add) => 
    {
        per.addressDescription = add.addressDescription;
        return per;
    });
Gilad Green
  • 36,708
  • 7
  • 61
  • 95