2016-07-11 9 views
3

Ich suche das Gegenstück von Msql Abfrage:C# Linq Lambda verbinden und wählen Syntax

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

Ich habe diese Anfrage:

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

Gibt es eine Möglichkeit Persons.addressDescription zu füllen, ohne einzeln zuweisen die anderen Eigenschaften von Persons? Stellen Sie sich vor, wenn Persons 10 weitere Eigenschaften haben.

Ich möchte aus mit Schleifen wie verzichten:

foreach(Person person in PersonList) 
{ 
    foreach(Address address in AddressList) 
    { 
    if(person.addressId == address.addressId){ 
     person.addressDescription = address.addressDescription 
    } 
    } 
} 
+0

Mögliche Duplikat [Was die Syntax für eine innere Verknüpfung in LINQ to SQL ist?] (Http: // Stackoverflow .com/questions/37324/what-is-the-syntax-fuer-inner-join-in-linq-to-sql) –

+0

@ shA.t Hallo und danke für Ihre Antwort, das Problem ist ihre Frage nur fragt wie Sie die Personen zurückgeben, ohne Persons.AddressDescription zu füllen. – user3770093

Antwort

3
var query = persons.join(address, 
    per = person.addressId, 
    add = addressId 
    (per,add) => 
    { 
     per.addressDescription = add.addressDescription; 
     return per; 
    }); 
+0

wow wirklich, das ist das erste Mal, dass ich eine Rückkehr in der Select-Anweisung sah. Ich werde es jetzt versuchen. – user3770093

+0

Ich kann keine Rückgabe-Funktion in der Abfrage verwenden =/ – user3770093

+0

@ user3770093 Zeigen Sie, was Sie getan haben, denn für mich funktioniert es –

0
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 
+0

danke für Ihre Antwort, aber ich denke, ich muss es immer noch nach Ihrem Beispiel Schleife. – user3770093