开发者

Select only first matches using a join on two tables (one-to-many relationship) in LINQ-to-Entities

I am using LINQ-to-Entities and need to populate a ListView using a select statement with a join.

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}

The problem is that because I have a one-to-many relationship I get multiple rows where there are more than one record with the same CustomerID in my A开发者_运维问答ddress table.

         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  

I would like to only bring back the first match for each CustomerID in my Address table.

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

Any Ideas?


You could try to rework that script using Fluent Linq Syntax, Adding .FirstOrDefault(),

Like so:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜