2016-10-25 131 views
0

我想要獲取客戶的地址列表。在我的數據庫中,Customer1有1個地址,Customer2有2個地址。加入使用LINQ LAMBDA

我與地址加入的客戶,像這樣:

var customers = _dbContext.Customer.Join(_dbContext.Address, c => c.Id, a => a.EntityId, (c, a) => new { Customer = c, Address = a }); 

我想的結果是2個客戶內部嵌套每個地址。相反,我得到3條記錄(每個地址的記錄),如下所示。有誰知道我可以如何調整我的查詢來獲得我期待的結果?謝謝!

[{"customer":{"id":1,"companyName":"Customer2","firstName":"Donald","lastName":"Trump"},"address":{"id":5,"entityId":1,"city":"Atlanta","state":"GA","zip":"33333"}}, 

{"customer":{"id":1,"companyName":"Customer2","firstName":"Bill","lastName":"Clinton"},"address":{"id":7,"entityId":1,"city":"Gainesville","state":"FL","zip":"33333"}}, 

{"customer":{"id":2,"companyName":"Customer1","firstName":"Tom","lastName":"Hanks"},"address":{"id":9,"entityId":2,"city":"Miami","state":"FL","zip":"33333"}}] 
+0

你想'GroupJoin'而不是'Join'。 – Enigmativity

回答

1

嘗試下面的代碼

var customers = _dbContext.Customer 
    .GroupJoin(
     _dbContext.Address, 
     c => c.Id, 
     a => a.EntityId, 
     (c, a) => new 
     { 
      c.Id, 
      c.CompanyName, 
      c.FirstName, 
      c.LastName,       
      Address = a.ToList() 
     } 
    ); 

或者使用查詢風格

var customers = from c in _dbContext.Customer 
    join a in _dbContext.Address on c.Id equals a.EntityId into g 
    select new 
    { 
     c.Id, 
     c.CompanyName, 
     c.FirstName, 
     c.LastName, 
     Address = g.ToList() 
    }; 
+0

工作很好。我確信下面的解決方案也可行,但這恰好是我第一次嘗試。謝謝! – Primico

0

這將解決您的問題。您需要將客戶分組,並循環查找每個客戶的地址。

var customers = _dbContext.Customer 
        .Join(_dbContext.Address 
        , c => c.Id 
        , a => a.EntityId, (c, a) => new { c.Id, Address = a }).GroupBy(j => j.Id); 

       foreach (var customer in customers) 
       { 
        Console.WriteLine($"Customer :{customer.Key} , Address : { customer.Count() }"); 
        foreach (var Addr in customer) 
        { 
         Console.WriteLine(Addr.xxxx); 
        } 
       }