2011-08-25 316 views
0

在兩個表中使用連接(一對多關係)只選擇第一個匹配我正在使用LINQ-to-Entities並需要使用select語句和連接來填充ListView。LINQ-to-Entities

dim db as New EntityModel 

Dim myList = From c in db.Customers.ToList 
      Join a in db.Addresses.ToList On c.AddressID Equals a.AddressID 
      Where c.CustomerID=1 
      Select New With {.CustomerID = c.CustomerID 
           .CustomerName = c.CustomerName 
           .PhysicalAddress = a.PhysicalAddress} 

的問題是,因爲我有一個一個一對多關係我得到那裏有我的地址表相同的客戶ID多條記錄多行。

  CustomerID  CustomerName  PhysicalAddress 
     1    Joe    12 Oak Street 
     1    Joe    37 Beech Street 
     1    Joe    19 Palm Avenue 
     2    Sabina   54 Rock Drive 
     2    Sabina   134 Rodeo Drive 

我想只帶回第一比賽對每個客戶ID在我的地址表。

  CustomerID  CustomerName  PhysicalAddress 
     1    Joe    12 Oak Street 
     2    Sabina   54 Rock Drive 

任何想法?

+1

莫非這幫助你嗎? http://stackoverflow.com/questions/1512471/linq-select-first-row – UrbanEsc

回答

1

您可以嘗試使用返工LINQ的流利的語法,腳本,添加.FirstOrDefault(),

像這樣:

var result = db.Customers.Select(
         x => new 
          { 
           CustomerName = x.Name, 
           PhysicalAdress = db.Adresses.Where(
             y => y.CustomerId == x.Id).FirstOrDefault().PhysicalAddress 
          }); 
相關問題