开发者

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

开发者 https://www.devze.com 2023-03-31 05:20 出处:网络
I am using LINQ-to-Entities and need to populate a ListView using a select statement with a join. dim db as New EntityModel

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

精彩评论

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